使用 iterrows() 时如何通过索引访问列

Xou*_*oul 3 python python-2.7 pandas

我想知道在iterrows用于遍历 DataFrame时如何使用索引而不是名称访问列。

这段代码是我能找到的最多的:

for index, row in df.iterrows():
    print row['Date']
Run Code Online (Sandbox Code Playgroud)

这是我用来遍历的另一种方法,但它似乎很慢:

for i in df.index:
    for j in range(len(df.columns)):       
                    df.ix[i,j] = 0
Run Code Online (Sandbox Code Playgroud)

Col*_*vel 5

您可以使用ix按索引访问:

In [67]: df
Out[67]:
       A  B
0  test1  1
1  test2  4
2  test3  1
3  test4  2

In [68]: df.ix[:,1]
Out[68]:
0    1
1    4
2    1
3    2
Name: B, dtype: int64
Run Code Online (Sandbox Code Playgroud)

使用第一列更新您的代码:

for index, row in df.iterrows():
    row.ix[0]
Run Code Online (Sandbox Code Playgroud)