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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32860833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:57:01  来源:igfitidea点击:

How to access column via index when using iterrows()

pythonpython-2.7pandas

提问by Xoul

I want to know how I can access columns using index rather than name when using iterrowsto traverse DataFrames.

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

This code is most I could find:

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

for index, row in df.iterrows():
    print row['Date']

This is another approach I took to traverse, but it seems very slow:

这是我用来遍历的另一种方法,但看起来很慢:

for i in df.index:
    for j in range(len(df.columns)):       
                    df.ix[i,j] = 0

采纳答案by Xoul

I figured it out. Iterate for i to number of columnsand use ias index to access columns:

我想到了。迭代i to number of columnsi用作索引来访问列:

for i in range(len(df.columns)):  
    for index, row in df.iterrows():    
        print row.ix[i]

回答by Colonel Beauvel

You can use ixto access by index:

您可以使用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

Updating your code with first column:

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

for index, row in df.iterrows():
    row.ix[0]