How to iterate over rows in a DataFrame in Pandas(如何在 Pandas 中遍历 DataFrame 中的行)
问题描述
我有一个来自 Pandas 的 DataFrame:
I have a DataFrame from Pandas:
import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
print df
输出:
c1 c2
0 10 100
1 11 110
2 12 120
现在我想遍历这个框架的行.对于每一行,我希望能够通过列名访问其元素(单元格中的值).例如:
Now I want to iterate over the rows of this frame. For every row I want to be able to access its elements (values in cells) by the name of the columns. For example:
for row in df.rows:
print row['c1'], row['c2']
在 Pandas 中可以做到这一点吗?
Is it possible to do that in Pandas?
我发现了这个 类似问题.但它并没有给我我需要的答案.例如,这里建议使用:
I found this similar question. But it does not give me the answer I need. For example, it is suggested there to use:
for date, row in df.T.iteritems():
或
for row in df.iterrows():
但我不明白 row 对象是什么以及如何使用它.
But I do not understand what the row object is and how I can work with it.
推荐答案
DataFrame.iterrows 是生成索引和行(作为系列)的生成器:
DataFrame.iterrows is a generator which yields both the index and row (as a Series):
import pandas as pd
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
df = df.reset_index() # make sure indexes pair with number of rows
for index, row in df.iterrows():
print(row['c1'], row['c2'])
10 100
11 110
12 120
这篇关于如何在 Pandas 中遍历 DataFrame 中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Pandas 中遍历 DataFrame 中的行
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
