2017-06-26 101 views
0

當我嘗試迭代數據幀時,不知何故dtype被改變。iterrows無法遍歷DataFrame Eror:touple對象沒有屬性「A」

dates = pd.date_range('20130101',periods=6) 
df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD')) 

df 
       A   B   C   D 
2013-01-01 -1.328046 -0.545127 -0.033153 1.190336 
2013-01-02 -0.549147 0.447161 1.179931 0.397521 
2013-01-03 -0.106707 -0.327574 -0.933817 -1.032949 
2013-01-04 -0.519988 -1.007374 -0.794482 -1.757222 
2013-01-05 -0.739735 1.220599 -1.387994 -0.116178 
2013-01-06 0.262876 -0.679471 -0.568768 -0.277880 

現在,當我嘗試遍歷行

for row in df.iterrows(): 
    print (row.A) 

我得到錯誤

AttributeError: 'tuple' object has no attribute 'A' 

我目前大熊貓的版本是0.20.1

謝謝。

+0

請閱讀[文檔](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iterrows。它返回索引的一個元組,並且每一行(作爲'Series')因此是錯誤,因此您想在df.iterrows()中爲行索引第二個元素:print(row [1])。 A)' – EdChum

回答

3

itterrows創建一個元組,那麼試試這個:

for pos, row in df.iterrows(): 
    print (row.A)