【发布时间】:2021-09-16 22:48:53
【问题描述】:
我有如下两个数据框,我在其中为唯一 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 中的值组合。
有人可以建议一种在 pandas 中执行此操作的方法吗?
【问题讨论】: