1

您好朋友,我想对包含数字和非数字列类型的数据框应用样式功能。如何避免以下错误?


错误: TypeError:(“'>'在'str'和'int'的实例之间不支持”,'发生在索引A')


在此处输入图像描述


import pandas as pd
d = {'A': ['A','B','C']}
data = pd.DataFrame(data=d)
data['B']=[7,8,9]
data['C']=[1,2,3]

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'white' if (val > 2) else 'black'
    return 'color: %s' % color

df_new = data.style.applymap(color_negative_red)

4

1 回答 1

2

如果更复杂的数据是创建自定义函数的一个想法 - 这里只选择带有 的数字列DataFrame.select_dtypes,将输出设置df1为空字符串并将数值替换为numpy.where

def color_negative_red(x):
    c1 = 'background-color: red'
    c2 = 'background-color: black' 

    cols = x.select_dtypes(np.number).columns
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    df1[cols] = np.where(x[cols] > 2, c1, c2)
    return df1

df.style.apply(color_negative_red, axis=None)
于 2019-10-09T12:00:06.023 回答