熊猫-按索引ID合并两个数据框

时间:2019-04-13 12:44:45

标签: python pandas

我有2个数据框,如下所示:

Dataframe1:

   6     count
store_1   10
store_2   23
store_3   53

Dataframe2:

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(而不是按列名)将Dataframe1Dataframe2合并。

2 个答案:

答案 0 :(得分:1)

索引的左合并将对您有用。

data = {'6': ['store1', 'store2', 'store3'], 'count': [10, 23, 53]}
df1 = pd.DataFrame(data).set_index('6')
df1

enter image description here

data = {'store_name': ['store1', 'store2'], 'location': ['location_a', 'location_b']}
df2 = pd.DataFrame(data).set_index('store_name')
df2

enter image description here

df1.merge(df2, left_index=True, right_index=True, how='left')

enter image description here

希望这会有所帮助。

答案 1 :(得分:0)

pd.concat([df1, df2], axis=1)

仅将df2的列(轴= 1)添加到第一个数据帧

相关问题