当尝试使用 pandas 中的 style.applymap() 为行索引列表中的特定列的几个单元格值着色时,出现错误“int”对象没有属性“index”。我不知道为什么数据框会这样?
def highlight_col(x, lst):
r = 'color: red'
df = pd.DataFrame('', index=x.index, columns=x.columns)
for i in lst:
df.iloc[i:1, 0] = r
return df
df1 = pd.DataFrame({'id':[10,11,12,13,14], 'name':['Rahul', 'Ravi', 'Mike', 'Nair', 'Mona'], 'age':[30,40,23,45,12], 'street_no':['E112', 'B115', 'C119', 'H112', 'J091']})
lst = (1, 3, 5) # list of row numbers
style1 = df1.style.applymap(lambda x: highlight_col(x, lst))
style1
Error: AttributeError: 'int' object has no attribute 'index'
IIUC,要将列
id
设置为红色,您可以使用 apply
尝试这种basic approach:
def highlight_row(ser, col, lst):
return ["color: red"
if i == df1.columns.get_loc(col) and ser.name+1 in lst
else "" for i in range(len(df1)-1)]
style1 = df1.style.apply(highlight_row, col="id", lst=[1, 3, 5], axis=1)
输出: