我尝试如下合并两个数据集(DataFrames):
D1 = pd.DataFrame({'Village':['Ampil','Ampil','Ampil','Bachey','Bachey','Center','Center','Center','Center'], 'Code':[123,324,190,453,321,786,456,234,987]})
D2 = pd.DataFrame({'Village':['Ampil','Ampil','Bachey','Bachey','Center','Center'],'Lat':[11.563,13.278,12.637,11.356,12.736,13.456], 'Long':[102.234,103.432,105.673,103.539,103.873,102.983]})
我想根据“乡村”列将两者合并。我希望输出如下所示:
D3 = pd.DataFrame({'Village': ['Ampil','Ampil','Bachey','Bachey','Center','Center'],'Code':[123,324,453,321,786,456],'Lat':[11.563,13.278,12.637,11.356,12.736,13.456], 'Long':[102.234,103.432,105.673,103.539,103.873,102.983]})
我尝试了加入,合并和合并,但都不符合目的。我需要一个适用于较大数据的代码。如果有人可以帮忙,我会非常感激。
答案 0 :(得分:1)
一种方法是先通过Village
为两个初始df创建一个运行中的累加器,然后通过Village
和count
合并:
df1['count'] = df1.groupby('Village').cumcount()
df2["count"] = df2.groupby('Village').cumcount()
print (df2.merge(df1,on=["Village","count"],how="left").drop("count",axis=1))
#
Village Lat Long Code
0 Ampil 11.563 102.234 123
1 Ampil 13.278 103.432 324
2 Bachey 12.637 105.673 453
3 Bachey 11.356 103.539 321
4 Center 12.736 103.873 786
5 Center 13.456 102.983 456