python - 根据条件比较 2 个数据框列后,如何创建新的 pandas 数据框?
问题描述
数据框 1
cust_id1 cust_id2
23 50
23 51
23 52
24 32
25 40
25 41
数据框 2
cust_id
50
51
52
32
40
对于每个 cust_id1,检查数据帧 1 的 cust_id2 是否存在于数据帧 2 的 cust_id 中。如果是,则创建一个新的数据帧。另外,我还想为 cust_id2 添加一个新的列数
新数据框中的预期输出 3
cust_id1 cust_id2 count_cust_id2
23 50 1
23 51 1
23 52 1
24 32 1
25 40 1
这是我尝试过的
uniq = df1['cust_id1'].dropna().unique()
cust_id_grouped = df1.groupby(['cust_id1'], as_index = False)
for i in uniq:
all_groups = cust_id_grouped.get_group(i)
count_cust_id2 = 0
for index, row in all_groups.iterrows():
if (row.cust_id1.isin(df2. cust_id)):
count_cust_id2 = count_cust_id2 + 1
Part 2 除了上面的数据框,我还有类似的数据框。
数据框 4
cust_id1 cust_id2
23 50
23 51
23 52
24 32
25 40
25 41
26 50
数据框 5
cust_id
50
51
52
32
40
41
50
预期输出应更新数据框 3,
cust_id1 cust_id2 count_cust_id2
23 50 2
23 51 2
23 52 2
24 32 2
25 40 2
25 41 1
26 50 1
我有多个这些数据框,每个组(df1-df2)和(df4-df5)代表一个月。计数实际上是当月的。
解决方案
用于Series.isin
测试所有值,不需要按组进行测试。最后获取计数GroupBy.transform
和GroupBy.size
:
df3 = df1[df1.cust_id2.isin(df2.cust_id)].copy()
df3['count_cust_id2'] = df3.groupby('cust_id2')['cust_id2'].transform('size')
print (df3)
cust_id1 cust_id2 count_cust_id2
0 23 50 1
1 23 51 1
2 23 52 1
3 24 32 1
4 25 40 1
推荐阅读
- c# - Xamarin Forms EntryCell 添加到 c# 中的现有 TableView 无法在 CustomViewModel 中访问
- python - 使用自定义损失函数时 model.fit() 出错
- stripe-payments - 通过 Stripe Checkout 支持免费试用
- android-download-manager - DownloadManager 无法在华为设备上运行
- html - 如何移动秤?
- python - 在 micropython 中重定向 Stderr?
- mysql - 使用具有相似列名的 sql 连接两个表
- google-cloud-platform - 谷歌云数据融合连接到informix
- python - Pandas .pivot_table() 按时间顺序重新排序索引
- state - 为什么我可以在 vuex 操作中使用 dayJS,但不能在 Vuex 存储中初始化状态?