2016-09-05 37 views

回答

1

我如何可以遍歷行的數據幀?由於某些原因,iterrows()返回元組而不是Series。

元組中的第二項是系列:

In [9]: df = pd.DataFrame({'a': range(4), 'b': range(2, 6)}) 

In [10]: for r in df.iterrows(): 
    print r[1], type(r[1]) 
    ....:  
a 0 
b 2 
Name: 0, dtype: int64 <class 'pandas.core.series.Series'> 
a 1 
b 3 
Name: 1, dtype: int64 <class 'pandas.core.series.Series'> 
a 2 
b 4 
Name: 2, dtype: int64 <class 'pandas.core.series.Series'> 
a 3 
b 5 
Name: 3, dtype: int64 <class 'pandas.core.series.Series'> 

我也明白,這是不使用熊貓的有效方式。

這是事實,一般來說,但這個問題有點過於籠統。您需要指定爲什麼要嘗試遍歷DataFrame。

2

用途:

s = pd.Series([0,1,2]) 

for i in s: 
    print (i) 
0 
1 
2 

DataFrame

df = pd.DataFrame({'a':[0,1,2], 'b':[4,5,8]}) 
print (df) 
    a b 
0 0 4 
1 1 5 
2 2 8 

for i,s in df.iterrows(): 
    print (s) 

a 0 
b 4 
Name: 0, dtype: int64 
a 1 
b 5 
Name: 1, dtype: int64 
a 2 
b 8 
Name: 2, dtype: int64 
相關問題