Rahul Varma
Rahul Varma

Reputation: 550

how to map column names with new dataframe and replace it with new values

I have a csv file as below df1:-

1  2  6  4
u  f  b  h
a  f  r  m
q  r  b  c

now I have another csv file as below df2:-

cat dog fish sand  vent wear
1   2    3    4      5   6

now I want to write a python code which should map column name with 2nd csv and replace the value and I have total 1900 columns in df2 which i need to map.

output csv

   cat dog   wear  sand
    u   f    b     h
    a   f    r     m
    q   r    b     c

can any one help me with this

Upvotes: 1

Views: 5502

Answers (1)

G. Anderson
G. Anderson

Reputation: 5955

You can use a dictionary to map df2 with df.rename()

#Convert df2 to dict and switch the string representations of the values with the keys
dct={str(v[0]):k for k,v in df2.to_dict(orient='list').items()}

df1.rename(mapper=dct, axis=1, inplace=True)

    cat dog wear    sand
0   u   f   b       h
1   a   f   r       m
2   q   r   b       c

df1.rename(mapper={str(v[0]):k for k,v in df2.to_dict(orient='list').items()}, axis=1, inplace=True)

Upvotes: 4

Related Questions