简体   繁体   中英

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.

This is my code: 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']

example 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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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