0

I have a dictionary that looks something like {1: 'Film & Animation', 2: 'Autos & Vehicles', ....... 10: 'Music'}

And I have a dataframe, with column names Name Address 1 2 3 .....

How can I change the dataframe column names to the corresponding values in the dictionary?

Output of print(thedict) {1: 'Film & Animation', 2: 'Autos & Vehicles', 10: 'Music', 15: 'Pets & Animals', 17: 'Sports', 18: 'Short Movies', 19: 'Travel & Events', 20: 'Gaming', 21: 'Videoblogging', 22: 'People & Blogs', 23: 'Comedy', 24: 'Entertainment', 25: 'News & Politics', 26: 'Howto & Style', 27: 'Education', 28: 'Science & Technology', 30: 'Movies', 31: 'Anime/Animation', 32: 'Action/Adventure', 33: 'Classics', 34: 'Comedy', 35: 'Documentary', 36: 'Drama', 37: 'Family', 38: 'Foreign', 39: 'Horror', 40: 'Sci-Fi/Fantasy', 41: 'Thriller', 42: 'Shorts', 43: 'Shows', 44: 'Trailers'}

Output of print(df.columns) = Index([24, 22, 25, 10, 17, 26, 23, 20], dtype='object')

kc9552
  • 25
  • 3
  • 10

1 Answers1

1

You can map the column names to your dictionary with:

df.columns = df.columns.map(thedict)

This will change the column names 'Name' and 'Address' to NaN.

You can then restore those column names with:

df.columns.values[0] = 'Name'
df.columns.values[1] = 'Address'
J. Bell
  • 406
  • 4
  • 3