gpt4 book ai didi

python - 根据用户输入条件删除行(Pandas、Python 3)

转载 作者:行者123 更新时间:2023-11-30 23:19:21 25 4
gpt4 key购买 nike

假设我有一个这样的 DF

  Words1            Score     
The Man 10
Right Hand 7
Bad Boy Company 7
Seven Deadly Sins 11

我希望做的是创建一个像这样的用户输入:

var = input("Enter the Words That Can Never Appear Together in the same phrase: ")

用户输入的单词不应一起出现在短语中。因此,可以说 var = Bad Company' DF 在 df.dropna() 之后变为

  Words1           Score     
The Man 10
Right Hand 7
Seven Deadly Sins 11

所以我有两个问题:有没有办法真正做到这一点?如果是这样,是否有办法支持多个查询,例如如果有人想要删除包含短语中出现“Bad”和“Company”的实例的行,以及删除出现“Seven”和“Sins”的任何行用一句话来说?

希望有人能帮助我!

最佳答案

您可以将“Words1”矢量化为一系列,然后应用正则表达式:

>>> df
Score Words
0 10 The Man
1 7 Right Hand
2 7 Bad Boy Company
3 11 Seven Deadly Sins
>>> df['Words'].str.contains('Bad')
0 False
1 False
2 True
3 False
Name: Words, dtype: bool
>>> df['Words'].str.contains('^(?=.*Bad)(?=.*Company)')
0 False
1 False
2 True
3 False
Name: Words, dtype: bool

然后使用这些 bool 值通过 bool 掩码删除您不需要的 bool 值:

>>> df=df[df['Words'].str.contains('^(?=.*Bad)(?=.*Company)')==False]
>>> df
Score Words
0 10 The Man
1 7 Right Hand
3 11 Seven Deadly Sins

[3 rows x 2 columns]
>>> df=df[df['Words'].str.contains('^(?=.*Sins)(?=.*Seven)')==False]
>>> df
Score Words
0 10 The Man
1 7 Right Hand

[2 rows x 2 columns]
<小时/>

将用户输入拆分为模式:

>>> s=raw_input('Words: ')
Words: Seven Sins
>>> s
'Seven Sins'
>>> pattern='^'+''.join('(?=.*{})'.format(word) for word in s.split())
>>> pattern
'^(?=.*Seven)(?=.*Sins)'

关于python - 根据用户输入条件删除行(Pandas、Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com