首页 > 解决方案 > 如何合并(使用DataFrame)具有相同输入但顺序不同的两个数据集

问题描述

我有两个数据集,其中一个本质上可以被视为描述符集,另一个包含信息。

我有一个简单的例子来说明我的意思。

import pandas as pd 

第一个数据集,即描述符:

df1 = pd.DataFrame({"color": ["blue", "yellow", "red"],
                    "abbv": ["b", "y", "r"]})

第二个数据集:

df2 = pd.DataFrame({"color_1": ["blue", "red", "yellow"],
                    "color_2": ["yellow", "blue", "red"],
                    "total": ["green", "purple", "orange"]})

我想要做的是使用 pd.merge 来合并两个数据集,使最终的数据集看起来像这样:

 | color_1 | color_2 | total | abbv_1 | abbv_2 |
 | ------- | ------- | ----- | ------ | ------ |
 |  blue   |  yellow | green |   b    |   y    |
      .          .       .       .        .
      .          .       .       .        .

标签: pandasdataframemerge

解决方案


可以使用创建映射df1系列set_index。然后可以添加新df2Series.map

# Create the Mapping Series
mapper = df1.set_index('color')['abbv']
# Add the New Columns
df2['abbv_1'] = df2['color_1'].map(mapper)
df2['abbv_2'] = df2['color_2'].map(mapper)

或者通过过滤列来迭代所有颜色列str.contains

mapper = df1.set_index('color')['abbv']
for c in df2.columns[df2.columns.str.contains('color')]:
    df2[f'abbv_{c.rsplit("_", 1)[-1]}'] = df2[c].map(mapper)

df2

  color_1 color_2   total abbv_1 abbv_2
0    blue  yellow   green      b      y
1     red    blue  purple      r      b
2  yellow     red  orange      y      r

推荐阅读