我有一个熊猫数据帧,df:
c1 c2
0 10 100
1 11 110
2 12 120
如何迭代此数据帧的行?对于每一行,我希望能够通过列的名称访问其元素(单元格中的值)。例如:
for row in df.rows:
print(row['c1'], row['c2'])
我发现了一个类似的问题,建议使用以下任一项:
for date, row in df.T.iteritems():
for row in df.iterrows():
但我不知道row对象是什么,以及如何使用它。
我们有多种选择来做同样的事情,很多人都分享了他们的答案。
我发现以下两种方法既简单又有效:
DataFrame.iterrows()DataFrame.itertuples()
例子:
import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
print (df)
# With the iterrows method
for index, row in df.iterrows():
print(row["c1"], row["c2"])
# With the itertuples method
for row in df.itertuples(index=True, name='Pandas'):
print(row.c1, row.c2)
注意:itertples()应该比iterrows()快
有时,有用的模式是:
# Borrowing @KutalmisB df example
df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]}, index=['a', 'b'])
# The to_dict call results in a list of dicts
# where each row_dict is a dictionary with k:v pairs of columns:value for that row
for row_dict in df.to_dict(orient='records'):
print(row_dict)
结果是:
{'col1':1.0, 'col2':0.1}
{'col1':2.0, 'col2':0.2}
为了循环数据帧中的所有行并方便地使用每行的值,可以将命名元组转换为ndarray。例如:
df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]}, index=['a', 'b'])
在行上循环:
for row in df.itertuples(index=False, name='Pandas'):
print np.asarray(row)
结果是:
[ 1. 0.1]
[ 2. 0.2]
请注意,如果index=True,则将索引添加为元组的第一个元素,这对于某些应用程序来说可能是不可取的。
虽然iterrows()是一个很好的选项,但有时itertples()会快得多:
df = pd.DataFrame({'a': randn(1000), 'b': randn(1000),'N': randint(100, 1000, (1000)), 'x': 'x'})
%timeit [row.a * 2 for idx, row in df.iterrows()]
# => 10 loops, best of 3: 50.3 ms per loop
%timeit [row[1] * 2 for row in df.itertuples()]
# => 1000 loops, best of 3: 541 µs per loop