在 pandas 中,当尝试使用 style.applymap() 为数据框的一列的少数值着色时,出现错误“int”对象没有属性“index”

问题描述 投票:0回答:1

当尝试使用 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'
pandas dataframe jupyter-notebook styles apply
1个回答
0
投票

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)

输出:

© www.soinside.com 2019 - 2024. All rights reserved.