[英]Add a TOTAL row to a pandas dataframe
我有一个 dataframe 如下:
POSITIVE NEGATIVE MASTER Net Positivity
Speaker
Mike 36.0 29.0 2187.0 0.32%
Rob 36.0 35.0 2413.0 0.04%
May 2.0 4.0 369.0 -0.54%
我想在最后添加一行,总正数 (36+36+2)、总负数 (29+35+4)、总 MASTER (2187+2413+369)。 新行的索引应该是“TOTAL”。 总净阳性率为(总阳性 - 总阴性)/总主。
POSITIVE NEGATIVE MASTER Net Positivity
Speaker
Mike 36.0 29.0 2187.0 0.32%
Rob 36.0 35.0 2413.0 0.04%
May 2.0 4.0 369.0 -0.54%
TOTAL 74.0 68.0 4969.0 0.12%
我应该如何在 pandas 中添加这一总行?
你可以简单地
newdf = pd.concat([df, df.sum()]
newdf.rename(index={index[-1]:"Total"}, inplace=True)
尝试这个:
df = df.append(df.sum(numeric_only=True), ignore_index=True)
df['Net_Positivity'] = (df['POSITIVE']-df['NEGATIVE'])*100/df['MASTER']
df['Speaker'].fillna('Total', inplace=True)
df.set_index('Speaker', inplace=True)
print(df)
POSITIVE NEGATIVE MASTER Net_Positivity
Speaker
Mike 36.0 29.0 2187.0 0.320073
Rob 36.0 35.0 2413.0 0.041442
May 2.0 4.0 369.0 -0.542005
Total 74.0 68.0 4969.0 0.120749
您可以使用loc
在 df 上添加行和sum
。 然后用正确的格式计算净正数
df.loc['total'] = df.iloc[:, :-1].sum()
df.loc['total', 'Net Positivity'] = f"""{(df.loc['total', 'POSITIVE']
- df.loc['total', 'NEGATIVE'])
/df.loc['total', 'MASTER']:.2%}"""
POSITIVE NEGATIVE MASTER Net Positivity
Speaker
Mike 36.0 29.0 2187.0 0.32%
Rob 36.0 35.0 2413.0 0.04%
May 2.0 4.0 369.0 -0.54%
total 74.0 68.0 4969.0 0.12%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.