【问题标题】:Checking if column in dataframe contains any item from list of strings检查数据框中的列是否包含字符串列表中的任何项目
【发布时间】:2020-11-10 21:20:26
【问题描述】:

我的目标是检查我的数据框列,如果该列包含字符串列表中的项目(在 ex 中匹配),那么我想创建一个包含所有匹配项的新数据框。

使用我当前的代码,我可以获取匹配列的列表,但是,它将它作为一个列表,我想用我以前的信息创建一个新的数据框。

这是我当前的代码 - 我想要我以前拥有的整个数据框信息,而不是生成一个列表

matches = ['beat saber', 'half life', 'walking dead', 'population one']
checking = []
for x in hot_quest1['all_text']:
    if any(z in x for z in matches):
        checking.append(x)

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    Pandas 通常允许您过滤数据帧,而无需使用 for 循环。

    这是一种可行的方法:

    matches = ['beat saber', 'half life', 'walking dead', 'population one']
    
    # matches_regex is a regular expression meaning any of your strings: 
    # "beat saber|half life|walking dead|population one"
    matches_regex = "|".join(matches)
    
    # matches_bools will be a series of booleans indicating whether there was a match
    # for each item in the series
    matches_bools = hot_quest1.all_text.str.contains(matches_regex, regex=True)
    
    # You can then use that series of booleans to derive a new data frame 
    # containing only matching rows
    matched_rows = hot_quest1[matches_bools]
    

    这是str.contains 方法的文档。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html

    【讨论】:

    • 这正是我想要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 2012-11-15
    • 2023-03-27
    • 1970-01-01
    • 2020-04-02
    • 2016-01-27
    相关资源
    最近更新 更多