【问题标题】:How to add multiple strings to .str.contains in pandas? [duplicate]如何在 Pandas 中向 .str.contains 添加多个字符串? [复制]
【发布时间】:2021-11-28 12:03:00
【问题描述】:

检查我提供的代码,检查 m1 和 m2 的部分,我在那里发表了评论。我想添加多个字符串,这里有简单的解决方案吗?

我知道这不是这样做的方法,但这只是我想出的解决方案。如果您有其他相同想法的解决方案,请提供。

import pandas as pd
NewDataFrame = pd.DataFrame({'Group':['aaa','bbb','ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh'],
                                  'N':[1,2,3,4,5,6,7,8]})


def highlight_cells(x):
    c2 = 'background-color: #00FF00'
    c1 = 'background-color: red'
    c = 'background-color: white'

    m1 = NewDataFrame['Group'].str.contains("aaa", na=False) # here to add more strings ("bbb", "ggg") 
    m2 = NewDataFrame['Group'].str.contains("ccc", na=False) # here to add additional strings ("fff")
    #how to add more then one string, not to add new line for every string?
    
    colordata = pd.DataFrame(c, index=x.index, columns=x.columns)
    colordata.loc[m1, 'Group'] = c1
    colordata.loc[m2, 'Group'] = c2
    return colordata

end = StartingDataFrame.style.apply(highlight_cells,axis=None)

end

【问题讨论】:

    标签: python pandas dataframe pandas-styles


    【解决方案1】:

    使用| 添加字符串,例如:

    def highlight_cells(x):
        c2 = 'background-color: #00FF00'
        c1 = 'background-color: red'
        c = 'background-color: white'
    
        m1 = NewDataFrame['Group'].str.contains("aaa|bbb|ggg", na=False) 
        m2 = NewDataFrame['Group'].str.contains("ccc|fff", na=False) 
        #how to add more then one string, not to add new line for every string?
        
        colordata = pd.DataFrame(c, index=x.index, columns=x.columns)
        colordata.loc[m1, 'Group'] = c1
        colordata.loc[m2, 'Group'] = c2
        return colordata
    
    end = StartingDataFrame.style.apply(highlight_cells,axis=None)
    

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 2018-07-15
      • 1970-01-01
      • 2017-08-09
      • 2021-08-26
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      相关资源
      最近更新 更多