Python Pandas遍历行并访问列名 [英] Python Pandas iterate over rows and access column names

查看:427
本文介绍了Python Pandas遍历行并访问列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历Python Pandas数据框的行.在数据框的每一行中,我试图通过其列名引用行中的每个值.

I am trying to iterate over the rows of a Python Pandas dataframe. Within each row of the dataframe, I am trying to to refer to each value along a row by its column name.

这就是我所拥有的:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10,4),columns=list('ABCD'))
print df
          A         B         C         D
0  0.351741  0.186022  0.238705  0.081457
1  0.950817  0.665594  0.671151  0.730102
2  0.727996  0.442725  0.658816  0.003515
3  0.155604  0.567044  0.943466  0.666576
4  0.056922  0.751562  0.135624  0.597252
5  0.577770  0.995546  0.984923  0.123392
6  0.121061  0.490894  0.134702  0.358296
7  0.895856  0.617628  0.722529  0.794110
8  0.611006  0.328815  0.395859  0.507364
9  0.616169  0.527488  0.186614  0.278792

我使用了这种方法进行迭代,但这只是给了我一部分解决方案-选择后的在每次迭代中排成一行,如何按列名称访问行元素?

I used this approach to iterate, but it is only giving me part of the solution - after selecting a row in each iteration, how do I access row elements by their column name?

这就是我想要做的:

for row in df.iterrows():
    print row.loc[0,'A']
    print row.A
    print row.index()

我的理解是,该行是熊猫系列.但是我无法索引该系列.

My understanding is that the row is a Pandas series. But I have no way to index into the Series.

在遍历行的同时可以使用列名吗?

Is it possible to use column names while simultaneously iterating over rows?

推荐答案

我也喜欢itertuples()

for row in df.itertuples():
    print(row.A)
    print(row.Index)

由于行是一个命名的元组,因此,如果您要访问每一行的值,则应该更快

since row is a named tuples, if you meant to access values on each row this should be MUCH faster

速度运行:

df = pd.DataFrame([x for x in range(1000*1000)], columns=['A'])
st=time.time()
for index, row in df.iterrows():
    row.A
print(time.time()-st)
45.05799984931946

st=time.time()
for row in df.itertuples():
    row.A
print(time.time() - st)
0.48400020599365234

这篇关于Python Pandas遍历行并访问列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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