Python 如何用dict替换分组数据帧

Python 如何用dict替换分组数据帧,python,pandas,replace,pivot-table,pandas-groupby,Python,Pandas,Replace,Pivot Table,Pandas Groupby,我有一个数据帧: 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(),in

我有一个数据帧:

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}
我尝试了simple
df.replace({'brand':di})
,但似乎brand列不在数据框中,尽管我可以看到它。

您需要用
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传递给
重命名
时,当函数遇到
时,它将被
替换

你想要df=df.replace(di)
?初始值很大,所以需要很多时间。分组否则只有很少的entries它工作,我只是不明白它怎么知道重命名什么?我想它是
df=df的缩写。重命名(index=di)
index
是默认值,所以它工作。因为使用了replace columns
df=df.rename(columns=di)
所以如果我在date列中有'BMW',它仍然会被重命名?否,因为没有columns关键字。