在 python 中连接两个不相等的数据框并用 0 填充不存在的值的最优雅方法

Most elegant way to join two unequal data frames in python and fill-in non-existent values with 0

假设我有两个数据框 x_2016y_2017,列为 index01%date。我对 index% 列感兴趣。我遇到的问题 运行 是我需要它们成为索引为 W11 到 W15 的数据框,而不管列 % 中的值的年份如何,但由于索引不以周为单位完全重叠,我将有一些行需要用 0 填充。

x_2016


    index       0       1           %           date
    2016 W12    16.0    0           2.5         2016-03-28
    2016 W13    38.0    5.0         43.0        2016-04-04
    2016 W14    48.0    13.0        63.0        2016-04-11
    2016 W15    50.0    18.0        1.0         2016-04-18

y_2017

   index         0      1           %           date
   2017 W11     16.0    8.0         40.0        2017-03-13
   2017 W12     20.0    16.0        19.0        2017-03-27
   2017 W13     34.0    27.0        6.0         2017-04-03
   2017 W14     28.0    32.0        17.0        2017-04-10

最终数据框应该如下所示:

决赛

index     %_2016          %_2017
W11       0               40.0
W12       2.5             19.0
W13       43.0            6.0
W14       63.0            17.0       
W15       1.0             0

在 python 中执行此操作的最优雅方法是什么?

您需要将每个数据框中的 "Wxx" 信息提取到一个新列中,然后合并该列上的数据框。最后,select 只是感兴趣的列并按 W 值排序。

x_2016['W_index'] = x_2016['index'].str.extract('(W\d\d)', expand=True)

y_2017['W_index'] = y_2017['index'].str.extract('(W\d\d)', expand=True)

pd.merge(
    left=x_2016, 
    right=y_2017, 
    how='outer', 
    on='W_index', 
    suffixes=('_2016', '_2017'))[
        ['W_index', '%_2016', '%_2017']
    ].fillna(0).sort_values('W_index').reset_index(drop=True)

# returns:
   W_index  %_2016  %_2017
0      W11     0.0    40.0
1      W12     2.5    19.0
2      W13    43.0     6.0
3      W14    63.0    17.0
4      W15     1.0     0.0