如何在pandas数据帧的索引中使用map

问题描述 投票:0回答:2

我想使用索引上的值和一个将这些值转换为更有意义的字典的字典在pandas数据框上创建一个新列。我最初的想法是使用地图。我到达了一个解决方案,但它非常复杂,必须有一个更优雅的方式来做到这一点。建议?

#dataframe and dict definition
df=pd.DataFrame({'foo':[1,2,3],'boo':[3,4,5]},index=['a','b','c'])
d={'a':'aa','b':'bb','c':'cc'}

df['new column']=df.reset_index().set_index('index',drop=False)['index'].map(d)
python pandas dataframe
2个回答
0
投票

显式创建一个新系列有点短:

df['new column'] = pd.Series(df.index, index=df.index).map(d)

0
投票

to_series之后,你可以使用mapreplace

df.index=df.index.to_series().map(d)
df
Out[806]: 
    boo  foo
aa    3    1
bb    4    2
cc    5    3

或者我们考虑另一种方式

df['New']=pd.Series(d).get(df.index)
df
Out[818]: 
   boo  foo New
a    3    1  aa
b    4    2  bb
c    5    3  cc
© www.soinside.com 2019 - 2024. All rights reserved.