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

时间:2018-03-01 19:18:15

标签: python pandas dataframe

我想使用索引上的值和一个将这些值转换为更有意义的字典的字典在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)

2 个答案:

答案 0 :(得分:0)

明确地创建一个新系列有点短:

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

答案 1 :(得分:0)

class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( home: new Container( decoration: new BoxDecoration( image: new DecorationImage( image: new ExactAssetImage('assets/dog.png'), fit: BoxFit.cover, ), ), child: new BackdropFilter( filter: new ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), child: new Container( decoration: new BoxDecoration(color: Colors.white.withOpacity(0.0)), ), ), ), ); } } 之后,您可以使用to_seriesmap

replace

或者我们考虑另一种方式

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