如何将多个字符串添加到 pandas 中的 .str.contains?
How to add multiple strings to .str.contains in pandas?
检查我提供的代码,检查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
添加带有 |
的字符串,例如:
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)
检查我提供的代码,检查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
添加带有 |
的字符串,例如:
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)