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
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With