简体   繁体   English

按 pandas 分组的比率值

[英]Ratio values groupby pandas

Here is a DataFrame where I use the groupby() function to obtain the number of positive and negative occurrences per day.这是一个 DataFrame ,我使用groupby() function 来获取每天的正面和负面出现次数。

data = [['28-08-22', 'Positive'], ['28-08-22', 'Negative'],  ['28-08-22', 'Positive'], ['28-08-22', 'Positive'], ['27-08-22', 'Positive'], ['27-08-22', 'Negative'], ['27-08-22', 'Negative'], ['27-08-22', 'Negative']]

df = pd.DataFrame(data, columns=['Date', 'actions'])
df2 = df.groupby('Date')['actions'].value_counts(normalize=True)

print(df2)

I would like to calculate the ratio of those occurrences for each day, meaning dividing positive value / negative value for each day.我想计算每天发生这些事件的比率,这意味着每天除以positive value / negative value

Output and expected result Output 和预期结果

Also, if on a day the positive value is higher than the negative one, I would like the ratio to be positive.此外,如果在某一天正值高于负值,我希望该比率为正值。 If the negative value is higher than the positive, I would like the ratio to be negative.如果负值高于正值,我希望比率为负值。

I am new to python so definitely need your help.我是 python 的新手,所以绝对需要你的帮助。 Thank you!谢谢!

Try to do the following instead of calculation df2:尝试执行以下操作而不是计算 df2:

df = df.pivot_table(index='Date',columns='actions',aggfunc='size').reset_index().set_index('Date')

df['percent'] = df['Negative'] / df.sum(axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM