Pandas多索引DataFrame合并:合并后保留唯一units sold列
解决多索引DataFrame合并后保留单列的问题
你的问题出在使用merge方法时,因为两个DataFrame都包含同名的units sold列,merge会自动给它们加上_x和_y后缀来区分来源。由于两个DataFrame的Model值完全不重叠(德系和美系车无交集),其实更适合用行拼接的方式来合并,而不是关联合并。
最优解决方案:使用pd.concat
直接用pd.concat将两个DataFrame按行拼接,因为它们的索引结构完全一致,且Model值唯一,拼接后会自动保留单个units sold列:
import pandas as pd import numpy as np # 原有的DataFrame创建代码不变 german_cars_sold = pd.MultiIndex.from_product([['Tom','Jerry'], ['2022', '2023'], ['Q1', 'Q2', 'Q3', 'Q4'], ['Porsche', 'Audi', 'Benz']], names=['SalesPerson', 'Year', 'Quarter', 'Model']) columns = ['units sold'] german = pd.DataFrame(np.arange(48).reshape((len(german_cars_sold), len(columns))), index=german_cars_sold, columns=columns) US_cars_sold = pd.MultiIndex.from_product([['Tom','Jerry'], ['2022', '2023'], ['Q1', 'Q2', 'Q3', 'Q4'], ['Telsa', 'Ford', 'Jeep']], names=['SalesPerson', 'Year', 'Quarter', 'Model']) US = pd.DataFrame(np.arange(48).reshape((len(US_cars_sold), len(columns))), index=US_cars_sold, columns=columns) # 替换merge为concat combined = pd.concat([german, US])
如果坚持用merge的处理方式
如果一定要用merge,可以合并生成的两个后缀列,保留最终的单列:
combined = german.merge(US, on=['SalesPerson', 'Year', 'Quarter', 'Model'], how='outer') # 合并两列,取非空值 combined['units sold'] = combined['units sold_x'].combine_first(combined['units sold_y']) # 删除原有的两个后缀列 combined = combined.drop(columns=['units sold_x', 'units sold_y'])
说明
concat是最适合场景的方法,因为你的需求是合并两个无重叠行的DataFrame,本质是行堆叠,而非按键关联。combine_first会优先取左边列的值,左边为空时取右边列的值,正好匹配你Model唯一的场景,不会有冲突。
内容的提问来源于stack exchange,提问作者Novice Python charmer
相关产品推荐
相关产品推荐

