简体   繁体   English

如何对熊猫数据框进行分组并对另一列中的值求和

[英]How to groupby pandas dataframe and sum values in another column

I have a pandas dataframe with 3 columns (CHAR, VALUE, and WEIGHT).我有一个包含 3 列(CHAR、VALUE 和 WEIGHT)的 Pandas 数据框。

  • CHAR column contains duplicate values which I need to group ['A', 'A', 'A', 'B', 'B', 'C']. CHAR 列包含重复值,我需要将这些值分组 ['A'、'A'、'A'、'B'、'B'、'C']。

  • VALUE column has a unique value for every unique CHAR [10, 10, 10, 15, 15, 20]. VALUE 列对于每个唯一的 CHAR [10, 10, 10, 15, 15, 20] 都有一个唯一的值。

  • WEIGHT column has various values [1, 2, 1, 4, 4, 6]. WEIGHT 列有各种值 [1, 2, 1, 4, 4, 6]。

Consider an example of my initial dataframe:考虑我的初始数据框的示例:

在此处输入图片说明

I need to create a new dataframe which will have 3 columns.我需要创建一个包含 3 列的新数据框。

  • CHAR which will not have any duplicates CHAR 不会有任何重复
  • T_VALUE (total value) which will have a sum of this CHAR's value and all its weights T_VALUE(总价值),它将包含此 CHAR 的值及其所有权重的总和
  • T_WEIGHT (total weight) which will have a sum of this CHAR's weights T_WEIGHT(总重量),它将具有此 CHAR 的权重之和

Result would look like this:结果如下所示:

在此处输入图片说明

I would highly appreciate any help.我将不胜感激任何帮助。

You could use += instead:你可以使用+=代替:

newDF = df.groupby(['CHAR', 'VALUE'], as_index=False)['WEIGHT'].sum()
newDF['VALUE'] += newDF['WEIGHT']

I was actually able to answer my own question.我实际上能够回答我自己的问题。 Here is the solution:这是解决方案:

d = {'CHAR': ['A', 'A', 'A', 'B', 'B', 'C'],
     'VALUE': [10, 10, 10, 15, 15, 20], 
     'WEIGHT':  [1, 2, 1, 4, 4, 6]}
df = pandas.DataFrame(data=d)

newDF = df.groupby(['CHAR', 'VALUE'], as_index=False)['WEIGHT'].sum()
newDF['VALUE'] = newDF['VALUE'] + newDF['WEIGHT']

暂无
暂无

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

相关问题 如何使用非唯一列将具有求和值的熊猫Groupby数据框映射到另一个数据框 - How to map pandas Groupby dataframe with sum values to another dataframe using non-unique column 使用 pandas groupby 根据另一个值的重复范围对列的行求和 - sum rows of column based on a repeating range of values in another with pandas groupby 熊猫如何对一个列进行分组并根据另一列的最小唯一值过滤数据框? - How to pandas groupby one column and filter dataframe based on the minimum unique values of another column? 如何对熊猫数据框中的一列进行分组,然后对另一列进行sort_values排序? - How to groupby for one column and then sort_values for another column in a pandas dataframe? 如何在 Pandas 中的另一列分组后获取列值的总和? - How to Get Sum of column value, after groupby another column in Pandas? 带有groupby的熊猫数据框滚动总和列 - Pandas dataframe rolling sum column with groupby 在熊猫数据框中按特定月份和总和值分组 - Groupby certain months and sum values in pandas dataframe 通过另一列的分组值的总和对pandas数据框中的列进行归一化 - Normalize column in pandas dataframe by sum of grouped values of another column 熊猫数据框-将一列wrt与另一列中的值求和 - Pandas dataframe - Sum a column wrt to values in another column 如何将一个熊猫数据框的一列与另一个数据框的每一列相加? - How to sum a column of one pandas dataframe to each column of another dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM