import pandas as pd # 创建左边的示例 DataFrame data1 = {'ID': [1, 2, 3, 4], 'Name': ['Alice', 'Bob', 'Charlie', 'John']} df1 = pd.DataFrame(data1) df1.set_index('ID', inplace=True) # 设置 'ID' 列为索引 # 创建右边的示例 DataFrame data2 = {'Age': [25, 30, 35, 46]} df2 = pd.DataFrame(data2) df2.index = [1, 2, 4, 5] # 修改索引,确保和左边的 DataFrame 不重叠 # 使用 merge 方法以左边表的索引为准连接两个表 merged = pd.merge(df1, df2, left_index=True, right_index=True, how='left') # 打印连接后的 DataFrame print("left-------------") print(merged) # 使用 merge 方法以左边表的索引为准连接两个表 merged = pd.merge(df1, df2, left_index=True, right_index=True, how='outer') # 打印连接后的 DataFrame print("outer-------------") print(merged) # 使用 merge 方法以左边表的索引为准连接两个表 merged = pd.merge(df1, df2, left_index=True, right_index=True, how='inner') # 打印连接后的 DataFrame print("inner-------------") print(merged)
标签:index,DataFrame,merge,pd,print,True,连接 From: https://www.cnblogs.com/nicole-zhang/p/17613978.html