第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何使用對(duì)應(yīng)字典重命名pd.value_counts()索引

如何使用對(duì)應(yīng)字典重命名pd.value_counts()索引

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

3 回答

?
婷婷同學(xué)_

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊

這是我的解決方案:


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


查看完整回答
反對(duì) 回復(fù) 2021-05-11
?
牛魔王的故事

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊

這是一個(gè)更簡(jiǎn)單的解決方案:


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構(gòu)造一個(gè)字典,將整數(shù)映射到天氣類型列表。

  • dict.get與一起使用pd.Index.map。與不同pd.Series.apply,您不能直接傳遞字典,但可以傳遞可調(diào)用函數(shù)。

  • 直接更新索引,而不使用中間變量。


或者,您可以weather在使用之前將地圖應(yīng)用于pd.Series.value_counts。這樣,您無(wú)需更新結(jié)果索引。

df['weather'] = df['weather'].map(weathers_dict)
df_vc = df['weather'].value_counts()


查看完整回答
反對(duì) 回復(fù) 2021-05-11
?
搖曳的薔薇

TA貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊

分類數(shù)據(jù)

您可以將分類數(shù)據(jù)用于pd.CategoricalIndex.rename_categories

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

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


查看完整回答
反對(duì) 回復(fù) 2021-05-11
  • 3 回答
  • 0 關(guān)注
  • 501 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)