简体   繁体   English

熊猫-根据另一列的行总数创建新列的正确方法(试图在副本上设置的值)?

[英]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.

相关问题 Pandas - 创建新列 - 如果另一个列值在列表中(正确方式) - Pandas - Create new column - if another column value is in list (correct way) 熊猫-创建一个新列,并在另一列中填充观察值 - Pandas- Create a new column filled with the number of observations in another column Pandas-创建一个基于列值插入新行的表? - Pandas- creating a table that inserts new rows based on column values? 如何根据一组条件在 PANDAS 中创建一个新列,然后将新列设置为另一个字段的值 - How can I create a new column in PANDAS based on a set of conditions and then setting the new column to the value of another field Python Pandas-根据给定的窗口并从特定值开始计算特定列的总和 - Python Pandas- Calculate sum of a certain column based on a given window and starting at a certain value 根据 pandas 中另一列的值创建一个新列 - Create a new column, based on the value of another column in pandas 根据另一列的值在熊猫中创建新列 - Create new column in pandas based on value of another column Pandas:根据另一列的文本值创建新列 - Pandas : Create new column based on text value of another column Python Pandas 根据另一个列值创建新列 - Python Pandas create new column based on another column value Pandas - 根据另一列的条件值创建新列 - Pandas - create new column based on conditional value of another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM