Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access column via index when using iterrows()

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

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
like image 762
Xoul Avatar asked Dec 12 '25 02:12

Xoul


2 Answers

You can use ix to access by index:

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]
like image 164
Colonel Beauvel Avatar answered Dec 14 '25 16:12

Colonel Beauvel


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

for i in range(len(df.columns)):  
    for index, row in df.iterrows():    
        print row.ix[i]
like image 39
Xoul Avatar answered Dec 14 '25 16:12

Xoul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!