Pandas - 为具有混合类型列的数据框设计样式
Pandas - Styling a data frame with mixed type columns
朋友们大家好,
我想在包含数字和非数字列类型的数据框中应用样式函数。
我怎样才能避免下面的错误?
错误:
类型错误:(“'str' 和 'int' 实例之间不支持'>'”,'occurred 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)
如果有更复杂的数据,一个想法是创建自定义函数 - 这里仅选择具有 DataFrame.select_dtypes
, set output df1
to empty strings and replace numeric values by 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)
朋友们大家好, 我想在包含数字和非数字列类型的数据框中应用样式函数。 我怎样才能避免下面的错误?
错误: 类型错误:(“'str' 和 'int' 实例之间不支持'>'”,'occurred 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)
如果有更复杂的数据,一个想法是创建自定义函数 - 这里仅选择具有 DataFrame.select_dtypes
, set output df1
to empty strings and replace numeric values by 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)