[英]Pandas group by, filter & plot
I have a dataframe 我有一个数据帧
Date rule_name
Jan 1 2016 A
Feb 4 2016 B
Jun 6 2016 C
Feb 5 2016 B
Feb 9 2016 D
Jun 5 2016 A
And so on ... 等等 ...
I am hoping to get a dataframe for each rule similar to below: Eg Dataframe for rule_name A: 我希望获得类似于下面的每个规则的数据帧:例如,rule_name的数据帧A:
date counts (rule_name) %_rule_name
Jan 16 1 100
Feb 16 0 0
Jun 16 1 50
Eg Dataframe for rule_name B: 例如,rule_name B的数据帧:
date counts (rule_name) %_rule_name
Jan 16 0 0
Feb 16 2 66.6
Jun 16 0 0
Etc. 等等。
My current solution: 我目前的解决方案
rule_names = df['rule_name'].unique().tolist()
for i in rule_names:
df_temp = df[df['rule_name'] == i]
df_temp = df.groupby(df['date'].map(lambda x: str(x.year) + '-' + str(x.strftime('%m')))).count()
df_temp.plot(kind='line', title = 'Rule Name: ' + str(i))
As you can see I am unable to get the % of rule name and am only plotting the count_rule_name. 如您所见,我无法获取规则名称的百分比,而只是绘制count_rule_name。 I feel like there is (a) a solution and (b) a better solution then iterating through the each rule name and plotting but am unable to figure it out unfortunately.
我觉得有(a)解决方案和(b)更好的解决方案,然后迭代每个规则名称和绘图,但不幸的是我无法弄清楚。
Solution 解
Use df.Date.str.split().str[0]
to get months 使用
df.Date.str.split().str[0]
得到几个月
df.groupby([df.Date.str.split().str[0]]).rule_name.value_counts(True) \
.unstack(fill_value=0).mul(100).round(1)
Plot 情节
df.groupby([df.Date.str.split().str[0]]).rule_name.value_counts(True) \
.unstack(fill_value=0).mul(100).round(1).plot.bar()
Validate Counts 验证计数
df.groupby([df.Date.str.split().str[0], df.rule_name]).size().unstack(fill_value=0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.