如何在 Pandas 中向 .str.contains 添加多个字符串? [复制]
Posted
技术标签:
【中文标题】如何在 Pandas 中向 .str.contains 添加多个字符串? [复制]【英文标题】:How to add multiple strings to .str.contains in pandas? [duplicate] 【发布时间】: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
【问题讨论】:
【参考方案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)
【讨论】:
以上是关于如何在 Pandas 中向 .str.contains 添加多个字符串? [复制]的主要内容,如果未能解决你的问题,请参考以下文章