基于来自两个不同数据框的两列创建一个新列

数据挖掘 Python 熊猫
2021-09-28 03:23:58

我在第一个数据框中有一列称为“id”,在第二个数据框中有一列称为“first_id”,它指的是第一个数据框中的 id。如果 id 和 first_id 匹配,我需要创建一个值为 1 的新列,否则为 0。我试过这个,但我得到一个错误ValueError: Length of values does not match length of index

df2['new'] = np.where(df2[df2.first_id.isin(df1.id.values)], 1, 0)

我理解为什么会这样,因为df2df2[df2.first_id.isin(df1.id.values)]的长度不同,但我不能使它们相同。有任何想法吗?

2个回答

你快到了!

示例 DF:

In [387]: df1
Out[387]:
   id
0   1
1   2
2   3
3   4
4   5

In [388]: df2
Out[388]:
   first_id
0         7
1         6
2         5
3         1
4         3

解决方案:

In [389]: df2['new'] = df2.first_id.isin(df1.id).astype(np.int8)

结果:

In [390]: df2
Out[390]:
   first_id  new
0         7    0
1         6    0
2         5    1
3         1    1
4         3    1

可能是这样的?

df1 = pd.DataFrame(np.random.randint(0,5,size=(100, 1)), columns=list('A')) # random 1 column df
df2 = pd.DataFrame(np.random.randint(0,5,size=(100, 1)), columns=list('B')) # random 1 column df
df2["new"] = df2.apply(lambda row: 1 if row[0] == df1["A"][row.name] else 0, axis = 1) # lambda function to check if they match. row.name gets the index
df2