简体   繁体   English

如何在pandas中创建新列,该列是基于条件的另一列的总和?

[英]How do I create a new column in pandas which is the sum of another column based on a condition?

I am trying to get the result column to be the sum of the value column for all rows in the data frame where the country is equal to the country in that row, and the date is on or before the date in that row. 我试图使结果列成为数据框中所有行的值列的总和,其中国家/地区等于该行中的国家/地区,并且日期在该行中的日期或之前。

Date        Country ValueResult
01/01/2019  France  10  10
03/01/2019  England 9   9
03/01/2019  Germany 7   7
22/01/2019  Italy   2   2
07/02/2019  Germany 10  17
17/02/2019  England 6   15
25/02/2019  England 5   20
07/03/2019  France  3   13
17/03/2019  England 3   23
27/03/2019  Germany 3   20
15/04/2019  France  6   19
04/05/2019  England 3   26
07/05/2019  Germany 5   25
21/05/2019  Italy   5   7
05/06/2019  Germany 8   33
21/06/2019  England 3   29
24/06/2019  England 7   36
14/07/2019  France  1   20
16/07/2019  England 5   41
30/07/2019  Germany 6   39
18/08/2019  France  6   26
04/09/2019  England 3   44
08/09/2019  Germany 9   48
15/09/2019  Italy   7   14
05/10/2019  Germany 2   50

I have tried the below code but it sums up the entire column 我已经尝试了下面的代码,但它总结了整列

df['result'] = df.loc[(df['Country'] == df['Country']) & (df['Date'] >= df['Date']), 'Value'].sum()

按照日期排序,您可以执行以下操作:

df['Result'] = df.grouby('Coutry').Value.cumsum()

暂无
暂无

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

相关问题 Python Pandas:如何根据基于另一列的条件创建列? - Python Pandas: How do I create a column given a condition based on another column? Pandas:基于作为对象列表的另一列创建一个新列 - Pandas: Create a new column based on a another column which is a list of objects 如何在 pandas dataframe 中添加基于另一个列条件的新列 - How to add a new column based another column condition in pandas dataframe 如何使用基于pandas中另一列中的条件的值生成新列 - How to generate new column with values based on condition in another column in pandas Pandas 根据来自另一个 dataframe 的计数和条件创建新列 - Pandas Create new column based on a count and a condition from another dataframe 如何根据列表中的单词创建新的 Pandas 列 - How Do I Create New Pandas Column Based On Word In A List 熊猫数据框创建一个新列,其值基于另一列上的groupby sum - pandas dataframe create a new column whose values are based on groupby sum on another column 如何根据另一个 Dataframe 中的值在 Pandas Dataframe 中创建一个新列? - How to create a new column in a Pandas Dataframe based on values in another Dataframe? Python Pandas:如何插入一个新列,该列是另一列的下一个“n”(也可以是分数)值的总和? - Python Pandas: How to insert a new column which is a sum of next 'n' (can be a fraction also) values of another column? 如何根据 pandas 中的条件获取不同的列值? - How do I get different column value based on condition in pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM