如何在 Pandas 中将 DataFrame 的行迭代为系列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39333099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate the rows of a DataFrame as Series in Pandas?
提问by Atte Juvonen
How can I iterate over rows in a DataFrame
? For some reason iterrows()
is returning tuples rather than Series
. I also understand that this is not an efficient way of using Pandas.
如何遍历 a 中的行DataFrame
?出于某种原因iterrows()
返回元组而不是Series
. 我也明白这不是使用 Pandas 的有效方式。
采纳答案by Ami Tavory
How can I iterate over rows in a DataFrame? For some reason iterrows() is returning tuples rather than Series.
如何遍历 DataFrame 中的行?出于某种原因,iterrows() 返回元组而不是系列。
The second entry in the tuple is a 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'>
I also understand that this is not an efficient way of using Pandas.
我也明白这不是使用 Pandas 的有效方式。
That is true, in general, but the question is a bit too general. You'll need to specify why you're trying to iterate over the DataFrame.
总的来说,这是真的,但这个问题有点过于笼统。您需要指定尝试迭代 DataFrame 的原因。
回答by jezrael
Use:
用:
s = pd.Series([0,1,2])
for i in s:
print (i)
0
1
2
DataFrame
:
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