Python Pandas 遍历行并访问列名

标签 python pandas dataframe series

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

这是我所拥有的:

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

我使用了 this approach进行迭代,但它只给了我部分解决方案 - 在每次迭代中选择一行后,如何通过列名访问行元素?

这是我想要做的:

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

我的理解是该行是 Pandas series .但是我没有办法索引到系列中。

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

最佳答案

我也喜欢 itertuples()

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

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

速度跑:

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 遍历行并访问列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43619896/

相关文章:

python - 雄蕊地形图在 Cartopy 中不起作用

python - os.system 无法调用文件名中带有左括号 '(' 的文件

python - 使用带有 lambda 函数的 DataFrame.apply 将返回的元组/列表分配给多个列

python - 在另一个数据帧的列的帮助下过滤一个 Pandas 数据帧的理想方法是什么?

r - 如何合并r中数据框中的列标题

python - 尝试在 Python 中使用运算符方法时出现类型错误

python - 带复位条件的累计和

python - 为什么 loc 和 iloc 对 pandas DataFrame 的行进行切片的工作方式不同?

python - 将 DataFrame 拆分为两个 DataFrame 并过滤这两个 DataFrame 以获得相同的维度

python - Pandas Dataframe 转置为不同数量的列