猿问

如何使用对应字典重命名pd.value_counts()索引

我正在做一value_counts()列代表分类值的整数。


我有一个字典,将数字映射到与类别名称相对应的字符串。


我想找到具有相应名称的索引的最佳方法。由于我对我的4行解决方案不满意。


我目前的解决方案

df = pd.DataFrame({"weather": [1,2,1,3]})

df

>>>

   weather

0        1

1        2

2        1

3        3


weather_correspondance_dict = {1:"sunny", 2:"rainy", 3:"cloudy"}

现在,我如何解决问题:


df_vc = df.weather.value_counts()

index = df_vc.index.map(lambda x: weather_correspondance_dict[x] )

df_vc.index = index

df_vc

>>>

sunny     2

cloudy    1

rainy     1

dtype: int64

问题

我对那种非常乏味的解决方案不满意,您是否有针对这种情况的最佳实践?


开心每一天1111
浏览 477回答 3
3回答

婷婷同学_

这是我的解决方案:>>> weather_correspondance_dict = {1:"sunny", 2:"rainy", 3:"cloudy"}>>> df["weather"].value_counts().rename(index=weather_correspondance_dict)    sunny     2    cloudy    1    rainy     1    Name: weather, dtype: int64

牛魔王的故事

这是一个更简单的解决方案:weathers = ['sunny', 'rainy', 'cloudy']weathers_dict = dict(enumerate(weathers, 1))df_vc = df['weather'].value_counts()df_vc.index = df_vc.index.map(weathers_dict.get)解释使用dictwithenumerate构造一个字典,将整数映射到天气类型列表。dict.get与一起使用pd.Index.map。与不同pd.Series.apply,您不能直接传递字典,但可以传递可调用函数。直接更新索引,而不使用中间变量。或者,您可以weather在使用之前将地图应用于pd.Series.value_counts。这样,您无需更新结果索引。df['weather'] = df['weather'].map(weathers_dict) df_vc = df['weather'].value_counts()

摇曳的蔷薇

分类数据您可以将分类数据用于pd.CategoricalIndex.rename_categories:s = df['weather'].value_counts() s.index = pd.Categorical(s.index).rename_categories(weather_correspondance_dict)此功能在Pandas v0.21 +中可用。
随时随地看视频慕课网APP

相关分类

Python
我要回答