【问题标题】:pandas dataframe check if column contains string that exists in another column熊猫数据框检查列是否包含另一列中存在的字符串
【发布时间】:2020-06-26 21:34:40
【问题描述】:

我正在尝试了解 Dataframe,但我还是个初学者。 假设我有一个包含两列的 DataFrame:

Name       Description
Am         Owner of Am
BQ         Employee at BQ  
JW         Employee somewhere

我想检查名称是否也是描述的一部分,如果是,则保留该行。如果不是,请删除该行。在这种情况下,它将删除第 3 行(某处的 JW Employee)

【问题讨论】:

  • 看时间和答案。你可以自己测试一下。速度很重要

标签: python pandas dataframe csv


【解决方案1】:
s='|'.join(df.Name)#Join the search words into a pattern
df=df[df.Description.str.contains(s)]#Mask using boolean select
print (df)

 Name     Description
0   Am     Owner of Am
1   BQ  Employee at BQ


%%timeit
s='|'.join(df.Name)
df[df.Description.str.contains(s)]
537 µs ± 2.37 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit df[df.apply(lambda x: x['Name'] in x['Description'], axis = 1)]
1.27 ms ± 3.22 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

【讨论】:

  • 这个答案更快,在大型数据集中为您提供更好的服务
【解决方案2】:

试试这个:

df[df.apply(lambda x: x['Name'] in x['Description'], axis = 1)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2021-01-16
    • 2023-03-03
    • 2021-09-02
    • 2015-09-05
    • 2018-01-28
    • 1970-01-01
    相关资源
    最近更新 更多