如何将 DataFrame 的行迭代为 Pandas 中的系列?
How to iterate the rows of a DataFrame as Series in Pandas?
如何遍历 DataFrame
中的行?出于某种原因 iterrows()
返回元组而不是 Series
。我也明白这不是使用 Pandas.
的有效方法
使用:
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
How can I iterate over rows in a DataFrame? For some reason iterrows() is returning tuples rather than 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.
大体上是这样,但是这个问题有点太笼统了。您需要说明您尝试遍历 DataFrame 的原因。
如何遍历 DataFrame
中的行?出于某种原因 iterrows()
返回元组而不是 Series
。我也明白这不是使用 Pandas.
使用:
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
How can I iterate over rows in a DataFrame? For some reason iterrows() is returning tuples rather than 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.
大体上是这样,但是这个问题有点太笼统了。您需要说明您尝试遍历 DataFrame 的原因。