Python和Pandas - 如何使用iterrows访问列

41

wowee.....如何在Python和Pandas中使用iterrows?如果我进行行迭代,我是否能够通过row ['COL_NAME']访问列?

这是列名:

print df
Int64Index: 152 entries, 0 to 151
Data columns:
Date          152  non-null values
Time          152  non-null values
Time Zone     152  non-null values
Currency      152  non-null values
Event         152  non-null values
Importance    152  non-null values
Actual        127  non-null values
Forecast      86  non-null values
Previous      132  non-null values
dtypes: object(9)

for row in df.iterrows():
    print row['Date']

Traceback (most recent call last):
  File "/home/ubuntu/workspace/calandar.py", line 34, in <module>
    print row['Date']
TypeError: tuple indices must be integers, not str

如果我打印一行:

(0, Date                                                 Sun Apr 13
Time                                                      17:30
Time Zone                                                   GMT
Currency                                                    USD
Event         USD Fed's Stein Speaks on Financial Stability ...
Importance                                                  Low
Actual                                                      NaN
Forecast                                                    NaN
Previous                                                    NaN
Name: 0)
2个回答

75

iterrows会给你一个包含索引和行的元组(index, row),所以如果你采用如下方式,你就可以基本上以你想象的方式访问列:

iterrows会给你一个包含索引和行的元组(index, row),所以如果你采用如下方式,你就可以基本上以你想象的方式访问列:

for index, row in df.iterrows():
    print row['Date']

4
你是否遇到过row ['Date']返回该单个列的Series表示形式而不是实际值的情况?尽管在迭代iterrows()之外从数据帧中访问相同单元格的行为符合预期,但我现在正在遇到这种情况。 - kuanb
这是默认行为。为了避免这种情况,请尝试使用itertuples而不是iterrows。https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.itertuples.html#pandas.DataFrame.itertuples - eric_kernfeld

3
如果您想在数据库中迭代每一行并对其应用一个函数,您可能还需要考虑使用apply函数。
def print_row(r):
    print r['Date']

df.apply(print_row, axis = 1)       

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接