[英]Pandas- correct way to create a new column based on the sum of rows of another column (value trying to be set on a copy)?
I have a dataframe with dates, names, and values, and all I want to do is create a column that is the output of the total sum of values by date, then subtract that sum by the value for each name for that date. 我有一个包含日期,名称和值的数据框,我要做的就是创建一列,该列是按日期得出的总值总和的输出,然后将该总和减去该日期每个名称的值。 I've been able to do this, but am getting the common error: A value is trying to be set on a copy of a slice from a DataFrame.
我已经能够做到这一点,但是却遇到了常见的错误: A value is trying to be set on a copy of a slice from a DataFrame.
This is my code: df['ex_Term'] = df.groupby('name').Term.transform('sum') - df['Term']
这是我的代码: df['ex_Term'] = df.groupby('name').Term.transform('sum') - df['Term']
It's telling me to use the iloc function and after reading the documentation and trying this code, it still didn't work: df['ex_Term'] = df.groupby('name').loc[:,('Term')].sum()- df['Term']
它告诉我使用iloc函数,在阅读文档并尝试使用此代码后,它仍然不起作用: df['ex_Term'] = df.groupby('name').loc[:,('Term')].sum()- df['Term']
example df: 示例df:
name Country value delta
mike UK 1 -1
mike US 2 1
IIUC尝试使用assgin
df=df.assgin(ex_Term=df.groupby('name').Term.transform('sum') - df['Term'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.