python - 在熊猫数据框python中匹配列并突出显示结果
问题描述
我想在熊猫数据框中找到两列之间的匹配项并突出显示两列的结果,所以我做了以下代码:
df=pd.DataFrame({'Name':['Zea mays','Zea mays subsp. mexicana','Zea mays subsp. parviglumis'],'ID':[1,2,3],'type':[1.1,1.2,1.3],
'Name.1':['Zea mays subsp. huehuetenangensis','Zea mays subsp. mays','Zea mays'],'ID.1':[1,2,3],'type.1':[1.1,1.2,1.3],
'Name.2':['Zea nicaraguensis','Zea luxurians','Zea perennis'],'ID.2':[1,2,3],'type.2':[1.1,1.2,1.3],
'Name.3':['Capsicum annuum','Capsicum frutescens','Capsicum chinense'],'ID.3':[1,2,3],'type.3':[1.1,1.2,1.3]})
def in_statements(s):
color = 'yellow'
if np.where(str(s.iloc[4]) == str(s.iloc[8])):
color = 'yellow'
else:
color = 'black'
return 'background-color: %s' % color
df.style.applymap(in_statements)
但是,它给了我这个错误:“(“'str'对象没有属性'iloc'”,'发生在索引样本')”
这是一个输入示例:
有人可以指出我正确的方向吗?谢谢
解决方案
如果要突出显示Name
s 列中的重复值,请使用Styler.apply
掩码 creted byDataFrame.filter
为具有Name
、重新整形的列DataFrame.stack
、获取重复值Series.duplicated
并重新整形Series.unstack
:
df=pd.DataFrame({'Name':['Dog','Dog.1','Dog.3'],'ID':[1,2,3],'type':[1.1,1.2,1.3],
'Name.1':['Dog','cat','Dog.3'],'ID.1':[1,2,3],'type.1':[1.1,1.2,1.3],
'Name.2':['cat','cat.12','Dog.1'],'ID.2':[1,2,3],'type.2':[1.1,1.2,1.3],
'Name.3':['cat.7','cat.13','Dog.3'],'ID.3':[1,2,3],'type.3':[1.1,1.2,1.3]})
print (df)
Name ID type Name.1 ID.1 type.1 Name.2 ID.2 type.2 Name.3 ID.3 \
0 Dog 1 1.1 Dog 1 1.1 cat 1 1.1 cat.7 1
1 Dog.1 2 1.2 cat 2 1.2 cat.12 2 1.2 cat.13 2
2 Dog.3 3 1.3 Dog.3 3 1.3 Dog.1 3 1.3 Dog.3 3
type.3
0 1.1
1 1.2
2 1.3
def color(x):
c1 = 'background-color: yellow'
c = ''
#compare columns
names = x.filter(like='Name')
mask = names.stack().duplicated(keep=False).unstack()
#DataFrame with same index and columns names as original filled empty strings
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
#modify values of df1 column by boolean mask
df1 = names.mask(mask, c1).reindex(df1.columns, axis=1, fill_value='')
return df1
df.style.apply(color, axis=None).to_excel('df.xlsx', engine='openpyxl', index=False)
推荐阅读
- c - '* listeNote' 中对成员 'suivant' 的错误请求,它的指针类型为 'listenote {aka notes*}'(也许您打算使用 '->' ?)
- mysql - 使用带有 nodejs 的 mysql 准备查询时,Web 浏览器崩溃
- javascript - 如何使用 JavaScript 获取光标下的特定字符?
- python - 如何使用 python 和 multiwii 串行协议校准 mpu6050 传感器?
- python - 在 Keras 中获取子模型的层输出
- c++ - 从 QGraphicsItem foreach 循环中获取 QGraphicsSimpleTextItem 的字符串?
- mysql - 如果满足多对多关系条件,Laravel 仅显示模型?
- python - 如何多处理一个循环遍历python中每个像素的for循环?
- c# - OAuth授权问题理解c#中的流程和代码流
- python-3.x - 找不到硒元素