首页 > 解决方案 > 组合表比多个连接更好的方法?

问题描述

我有两个 dfs,df1 和 df2。我需要以一种可能需要多个左连接的方式组合 dfs,但我觉得有更好的方法来做到这一点。

df1 是一个位置表和与之相关的人员(id 号),它看起来像这样。

location person1 person2 person3 ... personn
1        12      450     2       ... 90
2        23      218     4       ... 3
3        1000    274     937     ... 318
....     ...     ...     ...     ... ...
1350     1       41      10      ... 101

df2 包含有关人员的信息。它看起来像这样:

person year action
1      2020 a
2      2020 a
3      2020 b
4      2020 c
1000   2020 a
1      2019 c
2      2019 b
3      2019 a
4      2019 c
...    ...  ...
1000   2019 b

理想情况下,我希望组合数据集如下所示:

location year action_a_count action_b_count action_c_count ... action_n_count
1        2020 1              0              0              ... ...
2        2020 0              1              1              ... ...
3        2020 1              0              0              ... ...
1350     2020 1              0              0              ... ...
1        2019 0              1              0              ... ...
2        2019 0              1              1              ... ...
3        2019 0              1              0              ... ...
1350     2019 0              0              1              ... ...
...      ...  ...            ...            ...            ... ...

现在我的直觉是做一系列的左连接,将每个人的动作输入 df1,然后找出一种方法来计算它们。

标签: pythonpython-3.xpandasfor-loopjoin

解决方案


您可以将 df1 重组为 2 列,即位置和人员。这将简化后续操作。

df1_new = df1.melt(id_vars='location', 
                   value_vars=df1.columns[1:], 
                   value_name='person')

df1_new = df1_new.drop('variable', axis=1)

现在您可以加入 df2 和 df1_new

combined = df2.join(df1_new.set_index('person'), on='person', how='left')

然后创建一个数据透视表

combined.pivot_table(index=['location', 'year'], columns='action',  aggfunc='count')

创建数据透视表后,您可以根据需要重命名列。


推荐阅读