我有这样一个dataframe ("MUNg"):
MUN_id Col1
1-2 a
3 b
4-5-6 c
...另一个数据文件("ppc")是这样的:
id population
0 1 20
1 2 25
2 3 4
3 4 45
4 5 100
5 6 50
...我需要在"MUNg“中创建一个列,该列包含通过与来自"pcc”的in对应的、存在于MUN_id中的所有人口之和而获得的总人口。
预期结果:
MUN_id Col1 total_population
1-2 a 45
3 b 4
4-5-6 c 195
...我不写我是如何做到这一点的,因为我对python并不熟悉,我也不知道如何去做。
MUNg['total_population']=?非常感谢!
发布于 2022-04-13 11:35:13
您可以将split和explode字符串放入新行,map填充数据和GroupBy.agg以获得和:
MUNg['total_population'] = (MUNg['MUN_id']
.str.split('-')
.explode()
.astype(int) # required if "id" in "ppc" is an integer, comment if string
.map(ppc.set_index('id')['population'])
.groupby(level=0).sum()
)产出:
MUN_id Col1 total_population
0 1-2 a 45
1 3 b 4
2 4-5-6 c 195https://stackoverflow.com/questions/71856690
复制相似问题