亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

開心每一天1111 2021-04-28 05:53:48
我正在做一value_counts()列代表分類值的整數。我有一個字典,將數字映射到與類別名稱相對應的字符串。我想找到具有相應名稱的索引的最佳方法。由于我對我的4行解決方案不滿意。我目前的解決方案df = pd.DataFrame({"weather": [1,2,1,3]})df>>>   weather0        11        22        13        3weather_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 = indexdf_vc>>>sunny     2cloudy    1rainy     1dtype: int64問題我對那種非常乏味的解決方案不滿意,您是否有針對這種情況的最佳實踐?
查看完整描述

3 回答

?
婷婷同學_

TA貢獻1844條經驗 獲得超8個贊

這是我的解決方案:


>>> 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


查看完整回答
反對 回復 2021-05-11
?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

這是一個更簡單的解決方案:


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()


查看完整回答
反對 回復 2021-05-11
?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

分類數據

您可以將分類數據用于pd.CategoricalIndex.rename_categories

s = df['weather'].value_counts()
s.index = pd.Categorical(s.index).rename_categories(weather_correspondance_dict)

此功能在Pandas v0.21 +中可用。


查看完整回答
反對 回復 2021-05-11
  • 3 回答
  • 0 關注
  • 499 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號