【问题标题】:Creating a new data frame from existing data frame based on multiple partial strings基于多个部分字符串从现有数据框创建新数据框
【发布时间】:2022-10-12 22:07:58
【问题描述】:

如何根据一列中值的多个部分字符串匹配从现有数据框中创建新的 pandas 数据框?

例如,如果我有一个数据框,其中一列包含“Commercial”、“Corporate”、“Private”的部分字符串,我想创建一个新的数据框,其中仅包含包含“Commercial”部分字符串的行和“Corporate”,同时忽略具有部分私有字符串的行。

【问题讨论】:

  • 使用一些代码稍微解释一下您的问题,这将有助于我们更好地理解。
  • 请提供足够的代码,以便其他人可以更好地理解或重现该问题。

标签: python pandas


【解决方案1】:

我将您的问题解释为想要匹配“商业”和“公司”而不是“私人”这两个词。

数据:

import pandas as pd
wantedWords = ['Commercial', 'Corporate']
notWantedWords = ['Private']
df = pd.DataFrame(['Commercial, Corporate, Private',
                   'Commercial, Corporate', 
                   'Commercial', 
                   'Corporate', 
                   'none of the words'], columns=['text'])

使用正则表达式:

reg = r'^{}'
ex = '(?=.*{})'
wantedWordMatch = reg.format(''.join(ex.format(w) for w in wantedWords))
notWantedWordMatch = reg.format(''.join(ex.format(w) for w in notWantedWords))

df['text'].str.contains(wantedWordMatch, regex=True)

0     True
1     True
2    False
3    False
4    False
Name: text, dtype: bool

~df['text'].str.contains(notWantedWordMatch, regex=True)

0    False
1     True
2     True
3     True
4     True
Name: text, dtype: bool

df[(df['text'].str.contains(wantedWordMatch, regex=True) & (~df['text'].str.contains(notWantedWordMatch, regex=True)))]

    text
1   Commercial, Corporate

使用所有()/任何():

df.text.apply(lambda string: all(word in string for word in wantedWords))

0     True
1     True
2    False
3    False
4    False
Name: text, dtype: bool

df.text.apply(lambda string: any(word not in string for word in notWantedWords))

0    False
1     True
2     True
3     True
4     True
Name: text, dtype: bool

df[df['text'].apply(lambda string: (all(word in string for word in wantedWords) & any(word not in string for word in notWantedWords)))]

    text
1   Commercial, Corporate


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 2016-10-14
    • 2019-02-02
    • 2021-11-28
    • 2016-10-14
    • 1970-01-01
    相关资源
    最近更新 更多