【问题标题】:Write a function that filters a dataset for rows that contains all of the words in a list of words编写一个函数,过滤数据集以查找包含单词列表中所有单词的行
【发布时间】:2022-01-08 00:07:08
【问题描述】:

我想获得一个包含列表中所有元素的子数据框。 我们以DataFrame为例。

my_dict = {
    'Job': ['Painting', 'Capentry', 'Teacher', 'Farming'],
    'Job_Detail': ['all sort of painting', 
                  'kitchen utensils, all types of roofing etc.',\
                  'skill and practical oriented teaching',\
                  'all agricultural practices']
          }
df = pd.DataFrame(my_dict)

输出如下:

    Job         Job_Detail
0   Painting    all sort of painting
1   Capentry    kitchen utensils, all types of roofing etc.
2   Teacher     skill and practical oriented teaching
3   Farming     all agricultural practices

my_lst = ['of', 'all']

我想用mylst 过滤df 以获得如下所示的sub_DataFrame:

    Job         Job_Detail
0   Painting    all sort of painting
1   Capentry    kitchen utensils, all types of roofing etc.

我试过df[df.Job_Detail.isin(['of', 'all']),但它返回一个空的DataFrame。

【问题讨论】:

  • 您的函数不应该也返回3 Farming all agricultural practices,因为它也包含“全部”吗?
  • 是的,不应该。 my_lst 中的所有元素都应该在Job_Detail 的行中。
  • 好吧,看来andor 更棘手一些。不过,我想我有一个解决方案。
  • 我编辑了我的解决方案以包含只选择同时具有“of”和“all”的行的代码

标签: python pandas filter


【解决方案1】:

我不是 pandas 专家,但这里最好使用的函数似乎是 str.contains

来自文档:

Series.str.contains(pat, case=True, flags=0, na=None, regex=True)


测试模式或正则表达式是否包含在系列或索引的字符串中。

根据给定的模式或正则表达式是否包含在系列或索引的字符串中,返回布尔系列或索引。

编辑:这个掩码使用or,而不是and

import pandas as pd
my_dict = {
    'Job': ['Painting', 'Capentry', 'Teacher', 'Farming'],
    'Job_Detail': ['all sort of painting', 
                  'kitchen utensils, all types of roofing etc.',
                  'skill and practical oriented teaching',
                  'all agricultural practices']
          }

my_lst = ['of', 'all']

df = pd.DataFrame(my_dict)

print(df)


mask = df.Job_Detail.str.contains('|'.join(my_lst), regex=True)

print(df[mask])

这是一个屏蔽 uing and 的解决方案:

import pandas as pd
my_dict = {
    'Job': ['Painting', 'Capentry', 'Teacher', 'Farming'],
    'Job_Detail': ['all sort of painting', 
                  'kitchen utensils, all types of roofing etc.',
                  'skill and practical oriented teaching',
                  'all agricultural practices']
          }

my_lst = ['of', 'all']

df = pd.DataFrame(my_dict)

print(df)

print("------")

masks = [df.Job_Detail.str.contains(word) for word in my_lst]
mask = pd.concat(masks, axis=1).all(axis=1)


print(df[mask])

【讨论】:

    【解决方案2】:

    @Lone 您的代码回答了一个不同的问题,但它帮助我找到了答案。谢谢,不胜感激。

    这是最接近我需要的:

    df[(df.Job_Detail.str.contains('of')) & (df.Job_Detail.str.contains('all'))]

    【讨论】:

    • 我的第二个答案应该和你的代码做同样的事情,但使用 my_lst 作为要搜索的字符串列表。
    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 2020-03-02
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    相关资源
    最近更新 更多