简体   繁体   中英

Using values in a pandas dataframe as column names for another

This is my first dataframe.

Date        0   1   2   3   
2003-01-31  CA  KY  ID  CO
2003-02-28  CA  KY  HI  CO 
2003-03-31  CA  KY  CO  HI 

This is my second dataframe.

Date        CA  KY  ID  CO  HI                                            
2003-01-31   5   3   4   5   1 
2003-02-28   2   7   8   4   5  
2003-03-31   6   3   9   3   5 

How do I get this dataframe to print as output?

Date         0   1   2   3                                                
2003-01-31   5   3   4   5
2003-02-28   2   7   5   4
2003-03-31   6   3   3   5

I am wondering if there is a way to use the whole dataframe as an index to another instead of having to loop through all the dates/columns.

You can use df.lookup with df.apply here.

# 
# df1.set_index('Date')
#              0   1   2   3
# Date
# 2003-01-31  CA  KY  ID  CO
# 2003-02-28  CA  KY  HI  CO
# 2003-03-31  CA  KY  CO  HI

# df2.set_index('Date')
#             CA  KY  ID  CO  HI
# Date
# 2003-01-31   5   3   4   5   1
# 2003-02-28   2   7   8   4   5
# 2003-03-31   6   3   9   3   5

def f(x):
    return 

df1.apply(f)
# df1.apply(lambda x: 

            0  1  2  3
Date
2003-01-31  5  3  4  5
2003-02-28  2  7  5  4
2003-03-31  6  3  3  5

This will print the values of dataframe df and the column name of dataframe df1.

print(df.rename(columns={i:j for i,j in zip(df.columns.tolist(),df1.columns.tolist())}))

if you want to make the changes permanent, add the parameter inplace=TRUE

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