【问题标题】:Populate values based on another dataframe根据另一个数据框填充值
【发布时间】: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 中的值基于no1no2 中的值组合,id2 中的值基于no3no4 中的值组合。 有人可以建议一种在 pandas 中执行此操作的方法吗?

【问题讨论】:

    标签: pandas dataframe


    【解决方案1】:

    只需分别分配它们

    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
    

    【讨论】:

    • 我可以看到这给出了所需的答案。但是,是否保证特定组合将对应于所有三列中的相同值,即df1 中的列iddf2 中的id1id2 列?
    猜你喜欢
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多