Reputation: 29094
I would like to loop through the rows and columns in a dataframe. My dataframe looks like this:
My code looks like this:
for index,j in usd_margin_data.iterrows():
print(index,j)
But I actually want is loop rows and column in the data.
Something like this:
for row in usd_margin_data.iterrows():
for column in list(usd_margin_data):
What is the best way to loop through rows and columns, where I need the index for each row and column?
The expected output
10 CME 1728005
10 HKEX 0
10 Nissan 1397464.22
...
Upvotes: 3
Views: 278
Reputation: 863611
For loop is possible use:
for r,j in usd_margin_data.iterrows():
for c, val in j.items():
print(r,c,val)
If want 3 columns DataFrame with remove missing values:
df = usd_margin_data.stack().rename_axis(('row','col')).reset_index(name='val')
And then for loop is possible use itertuples
:
for x in df.itertuples():
print (x.row, x.col, x.val)
Upvotes: 5