2016-12-30 198 views
3

我正在使用一個開放的數據集,記錄從1999年到2015年在學校的入學情況。但是,該數據集在CSV中預先分配了未來幾年的列,即使這些列是空的。使用pandas.read_csv時忽略無關逗號

的數據可以在http://www.gov.pe.ca/opendata/OD9%20Offical%20School%20Enrollments%201999%20-2015.csv

被視爲這是我的代碼:

#Read current open data set (OD34) from URL and store in an array called enrollment 
url = "http://www.gov.pe.ca/opendata/OD9%20Offical%20School%20Enrollments%201999%20-2015.csv?" 
col_names = ['School_Name','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015'] 
enrollment = pandas.read_csv(url, header=None, skiprows=1, names=col_names, nrows=2) 
print(enrollment) 
print(enrollment.shape) 
print(type(enrollment)) 

代碼中並轉值,但過度的逗號意味着有幾十個不同的NaN值的每個學校。 DataFrame確實顯示爲2,18陣列,但print(enrollment)顯示NaN值。

編輯:我添加na_filter=False到pandas.read_csv聲明,當我print(enrollment)但它看起來像每列(一年)的所有數據,而不是對準每年的招生數字外來NaN值都沒有了。

這裏是一個數據的例子。

School Name,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 
Alberton Elementary School,229,231,237,213,225,218,219,214,194,186,167,175,178,158,148,129,127,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 
+0

是在[dropna(http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html)數據幀的方法,你在找什麼? – Justin

+0

我完全可以使用dropna刪除NA後導入。查看我的編輯,我使用'na_filter = False'來實現相同的結果。 – jbiggley

+0

'enrollment.dropna(axis = 1)' – piRSquared

回答

0

我分析它是這樣的:

pandas.read_csv(url, index_col=0).filter(regex='\d{4}') 

貌似這個

enter image description here


它做什麼

  • index_col=0告訴大熊貓第一列是索引。這看起來很合理,並且在查看結果之後,感覺是對的。
  • 默認情況下,read_csv將假定有一個標題行。讓它。
  • filter(regex='\d{4}')只會傳遞四位數字標題的列。

所以一定要確保你把它分配給你想要的數據幀變量。

enrollment = pandas.read_csv(url, index_col=0).filter(regex='\d{4}') 
+0

太棒了! .filter(regex ='\ d {4}')正是我在解決方案中所尋找的。謝謝!不幸的是,我沒有足夠的信譽爲我的投票顯示,但我沒有投票答覆。 – jbiggley

+0

@ jbiggley不用擔心。新年快樂! – piRSquared