python 和 pandas - 如何使用 iterrows 访问列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23145928/
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
python and pandas - how to access a column using iterrows
提问by Tampa
wowee.....how to use iterrows with python and pandas? If I do a row iteration should I not be able to access a col with row['COL_NAME']?
wowee .....如何在python和pandas中使用iterrows?如果我进行行迭代,我应该无法访问带有 row['COL_NAME'] 的 col 吗?
Here are the col names:
以下是列名:
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
if I print 1 row:
如果我打印 1 行:
(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)
采纳答案by Marius
iterrows
gives you (index, row)
tuples rather than just the rows, so you should be able to access the columns in basically the same way you were thinking if you just do:
iterrows
为您提供(index, row)
元组而不仅仅是行,因此如果您这样做,您应该能够以与您想的基本相同的方式访问列:
for index, row in df.iterrows():
print row['Date']
回答by Acorbe
If you want to iterate across your database and apply a function to each row, you might also want to consider the apply function
如果要遍历数据库并将函数应用于每一行,您可能还需要考虑 apply 函数
def print_row(r):
print r['Date']
df.apply(print_row, axis = 1)