首页 > 解决方案 > 根据另一个数据框填充值

问题描述

我有两个数据框,如下所示,我在其中为唯一 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的组合。有人可以建议一种在熊猫中做到这一点的方法吗?no3no4

标签: pandasdataframe

解决方案


只需分别分配它们

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

推荐阅读