【问题标题】:Dynamic search : Pandas data frame query动态搜索:Pandas 数据框查询
【发布时间】:2020-09-15 19:23:20
【问题描述】:

我正在尝试使用字符串(单词或短语)用户输入来搜索特定列中的子字符串以查询结果。我怎样才能使它动态?即我想继续添加单词作为新查询来定位项目而无需定义它。

例如。如果输入是 - 'word1'; 它返回 df['column']

中所有带有 'word1' 的行

如果输入是 - 'word1 word2 wordn'; 它返回查询的所有行,如下所示:

x = input("Type to search for item : ")  # input phrase or word
words = x.split(' ')

query = df.loc[(df['Column'].str.contains(words[0]))
           &(df['Column'].str.contains(words[1]))
           &(df['Column'].str.contains(words[n]))
           ]

【问题讨论】:

    标签: python pandas string


    【解决方案1】:

    考虑使用带有AND 逻辑的正则表达式Series.str.contains

    words_pattern = r"(" + ")(".join(words) + ")"
    
    sub_df = df.loc[df['char'].str.contains(words_pattern, regex=True)]
    

    或者,根据使用正则表达式字符串分组的警告,使用Series.str.extract

    words_pattern = r"(" + ")(".join(words) + ")"
    
    res = df['char'].str.extract(words_pattern)
    sub_df = df.loc[res.dropna().index]
    

    【讨论】:

      【解决方案2】:

      怎么样

      submasks = [df['Column'].str.contains(s) for s in words]
      combined = np.vstack(submasks).all(axis=0)
      df[combined]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-03
        • 1970-01-01
        • 2018-12-24
        • 1970-01-01
        • 2022-11-01
        • 2011-09-26
        • 2012-04-01
        相关资源
        最近更新 更多