pandas - 根据另一个数据框填充值
问题描述
我有两个数据框,如下所示,我在其中为唯一 ID 创建了一个新列。
import pandas as pd
df1=pd.DataFrame({
'no1':[20,20,40,10,50],
'no2':[50,20,10,40,50]
})
df2=pd.DataFrame({
'no1':[20,20,40,10,50,10,20,40],
'no2':[50,20,10,40,50,40,20,10],
'no3':[20,50,10,20,40,20,40,10],
'no4':[50,50,40,20,10,20,10,40]
})
df1['id'] = df1.groupby(['no1', 'no2']).ngroup()
这给出了以下内容:
no1 no2 id
0 20 50 2
1 20 20 1
2 40 10 3
3 10 40 0
4 50 50 4
我想创建新列并根据df2
. 我想要以下内容:
no1 no2 no3 no4 id1 id2
0 20 50 20 50 2 2
1 20 20 50 50 1 4
2 40 10 10 40 3 0
3 10 40 20 20 0 1
4 50 50 40 10 4 3
5 10 40 20 20 0 1
6 20 20 40 10 1 3
7 40 10 10 40 3 0
中的值id1
基于 和 中的值的组合,no1
而中的值基于和no2
中的值id2
的组合。有人可以建议一种在熊猫中做到这一点的方法吗?no3
no4
解决方案
只需分别分配它们
df2['id1'],df2['id2'] = df2.groupby(['no1', 'no2']).ngroup(), df2.groupby(['no3', 'no4']).ngroup()
df2
Out[124]:
no1 no2 no3 no4 id1 id2
0 20 50 20 50 2 2
1 20 20 50 50 1 4
2 40 10 10 40 3 0
3 10 40 20 20 0 1
4 50 50 40 10 4 3
5 10 40 20 20 0 1
6 20 20 40 10 1 3
7 40 10 10 40 3 0
推荐阅读
- android - 如果 OpenAPI 生成器的 Moshi 中的值不匹配,如何回退枚举
- javascript - 如何在Javascript中恢复插入符号位置?
- python - 如何使用python解析.in文件并将内容写入.out文件
- scala - 将 scala 映射值与列表进行比较,并为列表中不存在的键返回默认值
- sql - 需要单独计算每个客户在选定日期的票数,以及每天的销售数量和总数
- python - centos 7机器中的python 3.6.7 UnicodeEncodingError
- amazon-web-services - 在 AWS Step Functions 中跨循环传递数据
- kubernetes - 在工作节点和控制平面之间引入代理后,Kubernetes 工作节点处于 NotReady 状态
- webhooks - 如何将函数应用与 SharePoint webhook 一起使用?
- angular - ng2-completer 选择事件未在鼠标单击时触发