Peter Klopp
Peter Klopp

Reputation: 13

How do I rename columns of a df with a for loop and new column names deriving from other df?

I made a dataframe from a bigger dataframe with a for loop and and the group by function. The multiindexed dataframe has the name 'Area' for all columns and the second level for all columns is called 'mean'. I am indexing the columns by iloc and wanted to give them names based on a different dataframe.

Could you help me out? If you have a completely different approach I am thankful too, of course.

bis=len(index_df['amount'])
for c, d in zip (index_df['amount'], (bis)): 
    num[c] = num.iloc[:,[d]]

I get the following error message: 'TypeError: zip argument #2 must support iteration'

Upvotes: 1

Views: 843

Answers (1)

jpp
jpp

Reputation: 164843

You can't iterate over an integer, but you can iterate over a range object, e.g. range(len(index_df.index)). But, in any case, = in Pandas is used for assignment, not for renaming, unless you combine it with pd.DataFrame.pop.

If each column of num relates to a value in index_df['amount'], and the relation is aligned by integer position, you can simply use assignment:

num.columns = index_df['amount']

And that's it, no manual iteration involved.

Upvotes: 1

Related Questions