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

How to replace grouped dataframe with dict pandas python

我有一个数据框:

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)

应用于此初始 DataFrame:

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}),但品牌列似乎不在数据框中,尽管我可以看到它。

您需要 rename 才能将 MultiIndex 的值替换为 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

当你将 dict 传递给 rename 时,当函数遇到 key 时,它将被 value 替换。