我有一本这样的词典:

[{'name': 'a', 'age': '20', 'value': '10'}, {'name': 'a', 'age': '30', 'value': '15'}, {'name': 'a', 'age': '40', 'value': '25'}, {'name': 'b', 'age': '20', 'value': '11'}, {'name': 'b', 'age': '30', 'value': '12'}, {'name': 'b', 'age': '40', 'value': '13'}...]

现在,我想添加一个具有相同名称的所有值的总和的新键,如下所示:

[{'name': 'a', 'age': '20', 'value': '10', 'sum': '50'}, {'name': 'a', 'age': '30', 'value': '15', 'sum': '50'}, {'name': 'a', 'age': '40', 'value': '25', 'sum': '50'}, {'name': 'b', 'age': '20', 'value': '11', 'sum': '36'}, {'name': 'b', 'age': '30', 'value': '12', 'sum': '36'}, {'name': 'b', 'age': '40', 'value': '13', 'sum': '36'}...]

我已经在使用Pandas 进行分组和聚合了.这在Pandas中也是可能的吗?或者有没有标准的Python变体?

推荐答案

是的,你可以使用Pandas 来实现这一点.以下是一个示例代码:

import pandas as pd

# create the dictionary
data = [{'name': 'a', 'age': '20', 'value': '10'},
        {'name': 'a', 'age': '30', 'value': '15'},
        {'name': 'a', 'age': '40', 'value': '25'},
        {'name': 'b', 'age': '20', 'value': '11'},
        {'name': 'b', 'age': '30', 'value': '12'},
        {'name': 'b', 'age': '40', 'value': '13'}]

# create a DataFrame from the dictionary
df = pd.DataFrame(data)

# convert the 'value' column to numeric values
df['value'] = pd.to_numeric(df['value'])

# create a new column 'sum' with the sum of 'value' for each 'name'
df['sum'] = df.groupby('name')['value'].transform('sum')

# convert the 'sum' column to string values
df['sum'] = df['sum'].astype(str)

# convert the DataFrame back to a list of dictionaries
result = df.to_dict(orient='records')

print(result)

此代码从字典创建一个Pandas DataFrame,将"Value"列转换为数值,按"name"对DataFrame进行分组,计算每个组的"Value"之和,并创建一个新列"sum",每个"name"的和为"Value".最后,它将‘sum’列转换为字符串值,并将DataFrame转换回字典列表.

输出应该是一个词典列表,其中 for each ‘name’添加了‘sum’列.

Python相关问答推荐

如何修复fpdf中的线路出血

每个组每第n行就有Pandas

Python如何让代码在一个程序中工作而不在其他程序中工作

如何在Python中增量更新DF

创建带有二维码的Flask应用程序,可重定向到特定端点

如何在Python中使用时区夏令时获取任何给定本地时间的纪元值?

在函数内部使用eval(),将函数的输入作为字符串的一部分

根据不同列的值在收件箱中移动数据

仿制药的类型铸造

如何检测背景有噪的图像中的正方形

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

沿着数组中的轴计算真实条目

如何从具有不同len的列表字典中创建摘要表?

用Python解密Java加密文件

组/群集按字符串中的子字符串或子字符串中的字符串轮询数据框

如何根据一列的值有条件地 Select 前N组?

UNIQUE约束失败:customuser. username

名为__main__. py的Python模块在导入时不运行'

isinstance()在使用dill.dump和dill.load后,对列表中包含的对象失败

Python全局变量递归得到不同的结果