python - 组合表比多个连接更好的方法?
问题描述
我有两个 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,然后找出一种方法来计算它们。
解决方案
您可以将 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')
创建数据透视表后,您可以根据需要重命名列。
推荐阅读
- mongodb - 如何使用 Wazuh 代理提取 mongodb 日志?
- karate - 空手道 UI 按钮点击支持
- autotools - 运行 autoconf 时将变量替换为 m4 宏
- java - HotSpot JVM的GC在什么情况下会将内存释放回OS?
- java - Hibernate DAO 无法使用带有 Spring Boot 和 thymeleaf 的下拉列表保存外键,我不想使用 jpa
- laravel - Laravel:从多个表中提取数据
- javascript - 使用键列表创建对象
- android - 在第一个 viewType 上收到 DiffUtil 有效负载数据,但我需要第二个 Viewtype
- ios - 反应原生 ios 创建可操作的通知
- amazon-web-services - AWS Eventbridge:捕获所有事件的模式