我正在尝试遍历 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/