【发布时间】:2018-03-12 21:35:15
【问题描述】:
我有一个数据框:
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}),但似乎品牌列不在数据框中,尽管我可以看到它。
【问题讨论】:
-
你想要
df = df.replace(di)吗? -
首字母很大,所以需要很多时间。否则分组只有几个条目
标签: python pandas replace pivot-table pandas-groupby