Python 如何在pandas中链接样式函数的条件? 这就是我想要实现的

Python 如何在pandas中链接样式函数的条件? 这就是我想要实现的,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个熊猫数据框-例如,这个: 0 1 2 0 110.718803 119.821042 -52.593518 1 65.180254 33.518722 -69.893688 2 -135.652788 -64.711718 -241.717819 3 237.781393 -56.865142 15.969767 4 141.585158 138.904568 -115.155063 5 1

我有一个熊猫数据框-例如,这个:

            0           1           2
0  110.718803  119.821042  -52.593518
1   65.180254   33.518722  -69.893688
2 -135.652788  -64.711718 -241.717819
3  237.781393  -56.865142   15.969767
4  141.585158  138.904568 -115.155063
5   10.030938  -59.274415   73.328127
6  106.937681   -3.604859   44.418938
7  -49.478211  -91.574908  160.340627
8  170.744019  -85.764809  246.141857
9  -94.246832   81.069700 -113.460438
根据3种情况,单元格的背景色应不同:
单元格=100应为蓝色
所有其他细胞

我就是这么做的 我编写了这个函数(基于Pandas文档中的信息:

def高亮显示_编号(行):
返回[

“背景色:红色;颜色:白色”如果单元格您可以编写一个普通for循环,而不是列表理解

def highlight_number(row):
    arr = []
    for cell in row:
        if  cell <= 0:
            arr.append('background-color: red; color: white')
        elif cell >= 100:
            arr.append('background-color: blue; color: white')
        else:
            arr.append('background-color: white; color: black')
    return arr
df.style.apply(highlight_number)
def高亮显示_编号(行):
arr=[]
对于行中的单元格:
如果单元格=100:
arr.append('背景色:蓝色;颜色:白色')
其他:
arr.append('背景色:白色;颜色:黑色')
返回arr
df.style.apply(突出显示编号)
输出:


我觉得最简单的方法是使用它,它接受一个条件列表和一个选择列表(比如if elif,也像else一样接受一个默认值),修改您的函数,并在
axis=None
上使用它,因为我们应用于整个数据帧(注意,您也可以对列的子集使用
子集

def突出显示_编号(数据帧):
条件=[dataframe 0)&(dataframe>=100)]#您的条件
选项=[“背景色:红色;颜色:白色”,
'背景色:蓝色;颜色:白色']
arr=np.select(条件、选项,'background-color:white;color:black')
返回pd.DataFrame(arr,index=DataFrame.index,columns=DataFrame.columns)
df.style.apply(突出显示编号,轴=无)


是的:根据我的出发点,迭代并将彩色单元格附加到空列表中。这是一个非常灵活的解决方案,因为它可以用于列的子集(与第一个答案相反)。但需要额外导入Numpy。
def highlight_number(row):
    arr = []
    for cell in row:
        if  cell <= 0:
            arr.append('background-color: red; color: white')
        elif cell >= 100:
            arr.append('background-color: blue; color: white')
        else:
            arr.append('background-color: white; color: black')
    return arr
df.style.apply(highlight_number)
def highlight_number(dataframe):
    
    conditions = [dataframe <=0,(dataframe>0) & (dataframe>=100)] #your conditions
    choices = ['background-color: red; color: white',
               'background-color: blue; color: white']
    arr = np.select(conditions,choices,'background-color: white; color: black')
    return pd.DataFrame(arr,index=dataframe.index,columns=dataframe.columns)


df.style.apply(highlight_number,axis=None)