gpt4 book ai didi

python - 如何用 dict pandas python 替换分组数据框

转载 作者:太空宇宙 更新时间:2023-11-03 14:41:39 26 4
gpt4 key购买 nike

我有一个数据框:

date | brand | red | blue | green
---------------------------------
2017 | BMW | 2 | 1 | 0
| GM | 0 | 1 | 0
2018 | BMW | 0 | 0 | 1
| GM | 1 | 2 | 0

这是以下行的结果:

pd.pivot_table(df.reset_index(),index=['date','brand'],columns='color',values='index',aggfunc='count').fillna(0)

应用于此初始数据帧:

date | brand | color
--------------------
2017 | BMW | red
2017 | GM | blue
2017 | BMW | blue
2017 | BMW | red
2018 | BMW | green
2018 | GM | blue
2018 | GM | blue
2018 | GM | red

是否可以以某种方式用字典替换分组数据框中的 BMW、GM 条目,比如说

di = {'BMW': 1, 'GM': 2}

我尝试了简单的df.replace({'brand': di}),但似乎品牌列不在数据框中,尽管我可以看到它。

最佳答案

您需要renameMultiIndex 的值替换为 di:

df = df.rename(di)
#same as
#df = df.rename(index=di)
print (df)
color blue green red
date brand
2017 1 1.0 0.0 2.0
2 1.0 0.0 0.0
2018 1 0.0 1.0 0.0
2 2.0 0.0 1.0

当您将字典传递给rename时,当函数遇到key时,它将被value替换。

关于python - 如何用 dict pandas python 替换分组数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46514923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com