简体   繁体   中英

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'

You can't iterate over an integer, but you can iterate over a range object, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM