python - 检查字符串是否在 pandas Dataframe 列中,并创建新的 Dataframe

标签 python pandas dataframe substring

我正在尝试检查字符串是否在 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)]

这个词是这样的:“生态鼓”

然后我这样做了:

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

最终结果是:

eco|drum

这是“word”列:

enter image description here

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

最佳答案

你的想法是对的。 .contains 将正则表达式模式匹配选项默认设置为 True。因此,您需要做的就是向正则表达式模式添加 anchor ,例如“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$

关于python - 检查字符串是否在 pandas Dataframe 列中,并创建新的 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44273686/

相关文章:

python - 如何访问和修改 LabTestRepository 类中的 __list_of_hospital_lab_test_ids?

python - Python数据结构的内存大小

python - 在 supervisord 下运行 python 时证书验证失败

字符串的Python连接

python - 如何在 Pandas 中执行 groupby 并计算原始数据集中每行的平均值

python - 尝试更新 Pandas 数据帧时获取 "RuntimeError: generator raised StopIteration"

python - 如何制作一个虚拟列来确定列单元格值是否重复?

python - 如何删除 pandas df 中具有相同值但顺序不同的行?

python - 在 Pandas 中将数据帧子集为多个数据帧

python - 有效地将自定义函数应用于 Pandas 中的组