如何在Pandas的DataFrame中迭代行? [英] How to iterate over rows in a DataFrame in Pandas?

查看:704
本文介绍了如何在Pandas的DataFrame中迭代行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自大熊猫的数据框架:

  import pandas as pd 
inp = [{'c1' 10,'c2':100},{'c1':11,'c2':110},{'c1':12,'c2':120}]
df = pd.DataFrame(inp)
打印df

输出:

  c1 c2 
0 10 100
1 11 110
2 12 120

现在我想迭代上面的框架的行。对于每一行,我想要能够通过列的名称访问其元素(单元格中的值)。所以,例如,我想要这样做:

  for df.rows中的行:
打印行['c1'],行['c2']

有可能在熊猫?



我发现。但它并没有给我我需要的答案。例如,建议在df.T.iteritems()中使用:

 日期,行:

  for df.iterrows()中的行:

但是我不明白 row object is and how I can work with it。

iterrows 是一种生成索引和行

 在[18]中:for index,df.iterrows()中的行:
....:print row [' c1'],行['c2']
....:
10 100
11 110
12 120
pre>

I have a DataFrames 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

Output:

   c1   c2
0  10  100
1  11  110
2  12  120

Now I want to iterate over the rows of the above frame. For every row I want to be able to access its elements (values in cells) by the name of the columns. So, for example, I would like to have something like that:

for row in df.rows:
   print row['c1'], row['c2']

Is it possible to do that in pandas?

I found 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():

or

for row in df.iterrows():

But I do not understand what the row object is and how I can work with it.

解决方案

iterrows is a generator which yield both index and row

In [18]: for index, row in df.iterrows():
   ....:     print row['c1'], row['c2']
   ....:     
10 100
11 110
12 120

这篇关于如何在Pandas的DataFrame中迭代行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆