根据另一个数据帧的 id 和值在一个数据帧上设置值

Setting value on one dataframe based on the id and value from another dataframe

我的数据帧有问题。

第一个数据框如下所示:


id     0    1    2    3

100    0    0    0    0
101    0    0    0    0
102    0    0    0    0
103    0    0    0    0

第二个数据框如下所示:

id     num

100    1
100    2
100    3
101    0
101    3
102    1
103    2
103    3

我想将第一个数据帧中的零更改为列中 "id" 表示的特定行中的零,这些列出现在列 "num" 中的第二个数据帧中,具体为 "id".所以最后我想将第一个数据框更改为:

id     0    1    2    3

100    0    1    1    1
101    1    0    0    1
102    0    1    0    0
103    0    0    1    1

我该怎么做?我知道我可以使用 for 循环(我已经准备好了),但是我的数据帧非常大,大约需要 4 个小时才能完成。我在考虑 pandas 中的映射,但我没有解决方案。

此致

使用 get_dummiesmax 作为指标值,如果需要计数值,请使用 sum 而不是 max:

df = pd.get_dummies(df2.set_index('id')['num']).max(level=0)
print (df)
     0  1  2  3
id             
100  0  1  1  1
101  1  0  0  1
102  0  1  0  0
103  0  0  1  1

如果可能,在第一个 DataFrame 中添加更多行或列 DataFrame.reindex:

df = (pd.get_dummies(df.set_index('id')['num']).max(level=0)
        .reindex(index=df1.index, columns=df1.columns, fill_value=0))

将第一个数据框命名为df1,将第二个数据框命名为df2,您可以旋转数据框df2

df2['value'] = 1
df1 = df2.pivot_table(index='id', columns='num', values='value', fill_value=0)

输出:

num  0  1  2  3
id             
100  0  1  1  1
101  1  0  0  1
102  0  1  0  0
103  0  0  1  1