【问题标题】:Pandas - Styling a data frame with mixed type columnsPandas - 使用混合类型列样式化数据框
【发布时间】:2020-02-06 18:04:48
【问题描述】:

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


错误: TypeError: ("'>' not supported between 'str' and 'int'", 'occured at index 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)

【问题讨论】:

    标签: python-3.x pandas pandas-styles


    【解决方案1】:

    如果更复杂的数据是创建自定义函数的一个想法 - 这里只选择带有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)
    

    【讨论】:

      猜你喜欢
      • 2016-04-12
      • 2018-05-12
      • 2020-08-04
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      相关资源
      最近更新 更多