【问题标题】:Check if string is in pandas Dataframe column, and create new Dataframe检查字符串是否在 pandas Dataframe 列中,并创建新的 Dataframe
【发布时间】:2017-10-31 14:30:06
【问题描述】:

我正在尝试检查字符串是否在 Pandas 列中。我尝试了两种方法,但它们似乎都在检查子字符串。

itemName = "eco drum ecommerce"
words = self.itemName.split(" ")
df.columns = ['key','word','umbrella', 'freq']
df = df.dropna()
df = df.loc[df['word'].isin(words)]

我也尝试过这种方式,但这也会检查子字符串

words = self.itemName.split(" ")
words = '|'.join(words)
df.columns = ['key','word','umbrella', 'freq']
df = df.dropna()
df = df.loc[df['word'].str.contains(words, case=False)]

这个词是这样的:"eco drum"

然后我这样做了:

words = self.itemName.split(" ")
words = '|'.join(words)

以这样的方式结束:

eco|drum

这是"word" 专栏:

谢谢,这样可以不匹配子串吗?

【问题讨论】:

    标签: python pandas dataframe substring


    【解决方案1】:

    你的想法是对的。 .contains 默认情况下将正则表达式模式匹配选项设置为 True。因此,您需要做的就是在您的正则表达式模式中添加锚点,例如"ball" 将变为 "^ball$"

    df = pd.DataFrame(columns=['key'])
    df["key"] = ["largeball", "ball", "john", "smallball", "Ball"]
    print(df.loc[df['key'].str.contains("^ball$", case=False)])
    

    更具体地提到您的问题,因为您要搜索多个单词,您必须创建正则表达式模式以提供给contains

    # Create dataframe
    df = pd.DataFrame(columns=['word'])
    df["word"] = ["ecommerce", "ecommerce", "ecommerce", "ecommerce", "eco", "drum"]
    # Create regex pattern
    word = "eco drum"
    words = word.split(" ")
    words = "|".join("^{}$".format(word) for word in words)
    # Find matches in dataframe
    print(df.loc[df['word'].str.contains(words, case=False)])
    

    代码words = "|".join("^{}$".format(word) for word in words) 被称为生成器表达式。给定['eco', 'drum'],它将返回此模式:^eco$|^drum$

    【讨论】:

    • 嘿@the-realtom,现在不在我的桌面上,所以我回家后会尝试一下。所以你是说,在这种正则表达式模式是变量的情况下,我会做这样的事情 df = df.loc[df['word'].str.contains("^words$", case=False)]谢谢,看来,这是正轨
    • 嘿@the-realtom 我试着做这样的事情,但新的熊猫数据框是空的 df = df.loc[df['word'].str.contains('^words$', case=False)]
    • 我更新了我的答案,我认为 words 是一个单词的字符串?
    • 嘿@the-realtom 这个词就像这个“生态鼓”然后我做了这个 words = self.itemName.split(" ") words = '|'.join(words) 以结束用这个eco|drum 谢谢,这样可以吗?谢谢,我会将它添加到我的原始消息中以使其更清晰。
    • 我的答案已经更新,有什么问题请告诉我。
    猜你喜欢
    • 2013-08-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2019-12-22
    • 2021-12-28
    相关资源
    最近更新 更多