【问题标题】:Remove row from pandas dataframe if it has 2 strings如果它有 2 个字符串,则从 pandas 数据框中删除行
【发布时间】:2018-05-23 06:36:34
【问题描述】:

如果它包含两个字符串,我正在寻找一种从熊猫数据框中删除一行的方法。如果它有一个,我可以做到,但无法让两者都工作。下面是我用来删除基于 1 个字符串的记录的代码,希望将其更改为包含另一个关键字

代码:

Vikings_dataframe_cleaned2=Vikings_dataframe_cleaned[Vikings_dataframe_cleaned.TweetText.str.contains("RT") == False]

要排除的字符串: 我想检查文本以确保它不包含@teddyb_h20 和@casekeenum7。

例子:

['@teddyb_h2o test test','@casekeenum7 and @teddyb_h2o are test','@casekeenum7 is the best right now']

然后代码应生成如下所示的数据框:

['@teddyb_h2o test test','@casekeenum7 is the best right now']

【问题讨论】:

  • 它是骗子,使用 Vikings_dataframe_cleaned[~Vikings_dataframe_cleaned.TweetText.str.contains("RT|'Your_other_string") ]
  • 我刚刚看到了消息线索,您能否发布一个数据框示例以及您要排除哪些字符串?
  • 我刚刚发布了,希望对您有所帮助。如果您需要更多信息,请告诉我
  • @Wen,让我们重新打开这个

标签: python string pandas


【解决方案1】:

样本df

df = pd.DataFrame({'col': ['@teddyb_h2o test test','@casekeenum7 and @teddyb_h2o are test','@casekeenum7 is the best right now','test test']})

    col
0   @teddyb_h2o test test
1   @casekeenum7 and @teddyb_h2o are test
2   @casekeenum7 is the best right now
3   test test

解决办法:

df[~(df.col.str.contains('@teddyb_h2o') & df.col.str.contains('@casekeenum7'))]

    col
0   @teddyb_h2o test test
2   @casekeenum7 is the best right now
3   test test

@Wen的建议,更优雅

df[~df['col'].str.contains(r'^(?=.*@teddyb_h2o)(?=.*@casek‌​eenum7)')]

【讨论】:

  • 我对这个解决方案投了反对票……祝你好运……为你的解决方案投赞成票 :-)
  • 我看到了,想弄清楚。请取消删除,我会删除我的
  • 不需要,如果您不介意也可以添加..df[~df['col'].str.contains(r'^(?=.*@teddyb_h2o)(?=.*@casekeenum7)')] :-)
  • 完美!这行得通。感谢大家的帮助! :)
  • 让我们保持这个网站的正确答案:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 2021-11-20
  • 1970-01-01
  • 2022-11-27
  • 2018-01-21
  • 1970-01-01
  • 2017-06-03
相关资源
最近更新 更多