gpt4 book ai didi

python - 如何获取另一个数据帧中基于第一个数据帧中的列值的值之和?

转载 作者:行者123 更新时间:2023-12-01 03:33:29 25 4
gpt4 key购买 nike

我有一个数据框

df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]})
>>> df
Color Value
0 Red 100
1 Red 150
2 Blue 50

我有第二个数据框 dfmain

dfmain = pd.DataFrame({'Color': ["Red","Blue","Yellow"]})
>>> dfmain
Color
0 Red
1 Blue
2 Yellow

我想获得带有每种颜色总和的结果数据框我的预期结果是

>>> result
Color sum
0 Red 250
1 Blue 50
2 Yellow 0

现在我正在使用循环。当运行大数据集时它会变得很慢。我想得到典型的pandas(或numpy)解决方案

最佳答案

您可以使用groupbyreindex 聚合 sum :

df = df.groupby('Color')['Value'].sum().reindex(dfmain.Color, fill_value=0).reset_index()
print (df)

Color Value
0 Red 250
1 Blue 50
2 Yellow 0

关于python - 如何获取另一个数据帧中基于第一个数据帧中的列值的值之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40603285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com