【问题标题】:Ifelse on pandas data frame based on strings row wise基于字符串逐行的熊猫数据框上的 ifelse
【发布时间】:2016-05-21 09:52:05
【问题描述】:

这很简单。任务是检查一列中的字符串是否包含存储在另一个字符串中的所有单词。基于此做一些事情。这是一个简单的例子

import pandas as pd

df = pd.DataFrame({'Strings':["The brown","fox smoked 6", "cigarettes per day", "in his cave"], 
'Set': ["Alpha", "Beta", "Gamma", "Delta"]})

... >>> df
     Set             Strings
0  Alpha           The brown
1   Beta        fox smoked 6
2  Gamma  cigarettes per day
3  Delta         in his cave
>>> 

现在我想检查 df["Strings"] 的每一行是否包含单词“smoked”和数字“6”(这里的第 3 行也是如此)。如果是这样,我需要新列 df["Result"] 等于 df["Set"] 但添加了“健康损害”字样。如果不只是复制 df["Set"] 中包含的内容。输出应如下所示:

... >>> df_final
     Set             Strings   Result
0  Alpha           The brown   Alpha
1   Beta        fox smoked 6   Beta health damaging
2  Gamma  cigarettes per day   Gamma
3  Delta         in his cave   Delta
>>>  

【问题讨论】:

    标签: python string if-statement pandas


    【解决方案1】:

    您可以构建您的 2 个条件的掩码并将其传递给 np.where

    In [20]:
    
    mask = (df['Strings'].str.contains('6')) & (df['Strings'].str.contains('smoked'))
    In [23]:
    
    et
    df['Result'] = np.where(mask, df['Set'] + ' health damaging', df['Set'])
    df
    Out[23]:
         Set             Strings                Result
    0  Alpha           The brown                 Alpha
    1   Beta        fox smoked 6  Beta health damaging
    2  Gamma  cigarettes per day                 Gamma
    3  Delta         in his cave                 Delta
    

    这里的掩码使用.str.contains 测试您的字符串是否存在,我们和条件一起制作掩码。

    【讨论】:

    • 谢谢!那很快。我会等一天再表扬你的回答——也许有人想出了另一种解决方案,但这个非常好。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 2018-04-26
    • 2014-01-08
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    相关资源
    最近更新 更多