我有一个数据框:
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})
,但似乎品牌列不在数据框中,尽管我可以看到它。
您需要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
当您将字典传递给rename
时,当函数遇到key
时,它将被value
替换。
我是一名优秀的程序员,十分优秀!