我
mport pandas as pd
customer1 = {'name': 'John Smith',"qty": 10, 'income': 35, 'email': '[email protected]'}
customer2 = {'name': 'John Smith', "qty": 10,'income': 28, 'phone': '555-555-5555',"other": "something", 'email': '[email protected]'}
customer3 = {'name': 'Bob Johnson',"qty": 10,'income': 20, 'address': '123 Main St', 'email': '[email protected]',"c2":"kanel","c3":"pong"}
customer3 = {'name': 'Joe Johnson', "qty": 10,'income': 8, 'address': '123 Main St', 'email': '[email protected]',"c2":"kanel","c3":"pong"}
data = [customer1, customer2, customer3]
df = pd.DataFrame.from_dict(data)
print(df)
我想把qty
和income
相加,如果有相同的名字,结果如下所示
result = [
{'name': 'John Smith', "qty": 20,'income': 63, 'phone': '555-555-5555',"other": "something", 'email': '[email protected]','email2': '[email protected]'},
{'name': 'Bob Johnson',"qty": 10,'income': 20, 'address': '123 Main St', 'email': '[email protected]',"c2":"kanel","c3":"pong"},
{'name': 'Joe Johnson', "qty": 10,'income': 8, 'address': '123 Main St', 'email': '[email protected]',"c2":"kanel","c3":"pong"}
]
1条答案
按热度按时间kmbjn2e31#
如果你只想合计quty/income的总和,那么使用
groupby.agg
,sum
作为方法,其他所有列first
。对于python < 3.9,你可以用途:
输出量:
邮件作为新栏目
如果您还希望在输出中显示电子邮件的新列,则可以将其聚合为列表,单独转换为
DataFrame
,然后将join
转换为输出:输出量: