[英]Pandas - Merging two dataframes by index ID
我有 2 个数据框,如下所示:
数据框1:
6 count
store_1 10
store_2 23
store_3 53
数据框2:
store_name location
store_1 location_a
store_2 location_b
我正在尝试加入上述两个数据帧,以便获得以下输出:
6 count location
store_1 10 location_a
store_2 23 location_b
store_3 53
我正在尝试使用列的索引 id 而不是列名将Dataframe1
与Dataframe2
合并。
对索引进行左合并对您有用。
data = {'6': ['store1', 'store2', 'store3'], 'count': [10, 23, 53]}
df1 = pd.DataFrame(data).set_index('6')
df1
data = {'store_name': ['store1', 'store2'], 'location': ['location_a', 'location_b']}
df2 = pd.DataFrame(data).set_index('store_name')
df2
df1.merge(df2, left_index=True, right_index=True, how='left')
希望这可以帮助。
pd.concat([df1, df2], axis=1)
只需将 df2 中的列(轴 = 1)添加到第一个数据框
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.