如何在Python中识别df1中包含df2中包含元素的行?

问题描述 投票:0回答:1

我想比较两个数据帧,我需要知道存储在 df1 中的对象是否也存在于我的 df2 中。

但是,由于有许多附加信息,我的 df2 的对象更长。

举个例子,我的 df1: df1 = pandas.DataFrame(data = {'data1' : ['S10321Nr1.1', 'S10321Nr2.1', 'S10321Nr3.1', 'S10321Nr4.1']})

然后,我的 df2: df2 = pandas.DataFrame(data = {'data2' : ['HPAFII/Counts/S10323Nr1/HPAFII.S10323Nr1.1.genes.raw.csv.gz', 'HPAFII/Counts/S10323Nr1/HPAFII.S10323Nr1.2.genes .raw.csv.gz.md5sum'、'HPAFII/Counts/S10323Nr10/HPAFII.S10323Nr1.3.genes.raw.csv.gz'、'HPAFII/Counts/S10323Nr10/HPAFII.S10323Nr4.1.genes.raw.csv .gz.md5sum']})

有没有办法获取 df1 行,其中 df1 中的数字也存在于 df2 中? 我希望它在 df1 中返回一个新列,例如:

df1 = pandas.DataFrame(data = {'data1' : ['S10321Nr1.1', 'S10321Nr2.1', 'S10321Nr3.1', 'S10321Nr4.1'], '真-假' : ['真' , '假', '假', '真']})

我已经尝试过以下策略,但它不能正常工作(返回nan):

df1["TrueFalse"] = df2['data_name'].apply(lambda x: 1 if any(i in x for i in df1) else 0)

df1['new_col'] = df1[~df1['data1'].isin(df2)]

谢谢!

python dataframe list comparison
1个回答
0
投票

以下代码可能会解决您的问题:

df1["indf2"] = df1.apply(
    lambda row: 1 if any(row["data1"] in i for i in df2["data2"]) else 0, 
    axis=1
)
# with 'df1.apply(..., axis=1)' statement will apply function to eacy row of df1
# 'for i in df2["data2"]' means we will get every row's string from df2["data2"], so we can use 'row["data1"] in i' to see if data of df1["data1"] presents in df2["data2"] column
© www.soinside.com 2019 - 2024. All rights reserved.