我想使用索引上的值和一个将这些值转换为更有意义的字典的字典在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)
显式创建一个新系列有点短:
df['new column'] = pd.Series(df.index, index=df.index).map(d)
在to_series
之后,你可以使用map
或replace
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