grumpycylon
grumpycylon

Reputation: 91

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.

Upvotes: 3

Views: 57

Answers (2)

Ch3steR
Ch3steR

Reputation: 20669

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

# If `Date` is not index.
# 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 df2.lookup(x.index, x)

df1.apply(f)
# df1.apply(lambda x: df2.lookup(x.index, 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

Upvotes: 1

Divyansh Tiwari
Divyansh Tiwari

Reputation: 95

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

Upvotes: 0

Related Questions