Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

python - Map dataframe index using dictionary

Why doesn't df.index.map(dict) work like df['column_name'].map(dict)?

Here's a little example of trying to use index.map:

import pandas as pd

df = pd.DataFrame({'one': {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}})
map_dict = {'A': 'every', 'B': 'good', 'C': 'boy', 'D': 'does', 'E': 'fine'}
df
'''
    one
A   10
B   20
C   30
D   40
E   50
'''

df['two'] = df.index.map(mapper=map_dict)

This raises TypeError: 'dict' object is not callable

Feeding it a lambda works:

df['two'] = df.index.map(mapper=(lambda x: map_dict[x])); df
'''
   one    two
A   10  every
B   20   good
C   30    boy
D   40   does
E   50   fine
'''

However, resetting the index and mapping on a column works as expected without complaint:

df.reset_index(inplace=True)
df.rename(columns={'index': 'old_ndx'}, inplace=True) #so there's no index name confusion
df['two'] = df.old_ndx.map(map_dict); df

'''
  old_ndx  one    two
0       A   10  every
1       B   20   good
2       C   30    boy
3       D   40   does
4       E   50   fine
'''
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not answering your question... Just giving you a better work around.
Use to_series() them map

df = pd.DataFrame({'one': {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}})
map_dict = {'A': 'every', 'B': 'good', 'C': 'boy', 'D': 'does', 'E': 'fine'}

df['two'] = df.index.to_series().map(map_dict)

df

   one    two
A   10  every
B   20   good
C   30    boy
D   40   does
E   50   fine

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...