【问题标题】:Remove Rows Based on User-Input Conditions (Pandas,Python 3)根据用户输入条件删除行 (Pandas,Python 3)
【发布时间】:2014-09-30 00:12:03
【问题描述】:

假设我有这样的 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      

所以我有两个问题:有没有办法真正做到这一点?如果是这样,如果有办法支持多个查询,例如,如果有人想要删除包含“坏”和“公司”出现在短语中的实例的行,以及删除出现“七”和“罪”的任何行一句话?

希望有人可以帮助我!

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    您可以将“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
    

    然后使用这些布尔值通过布尔掩码删除您不想要的布尔值:

    >>> 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)'
    

    【讨论】:

    • 这是一个非常棒的解决方案,谢谢 dawg :)。但是,有没有办法对此进行调整,以便用户可以输入正则表达式中使用的单词?
    猜你喜欢
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多