Pandas 样式:条件格式

Pandas Styling: Conditional Formatting

我将以下格式应用于 pandas 数据框。

数据如下:

{'In / Out': {'AAA': 'Out',
  'BBB': 'In',
  'Total1': 'Out',
  'CCC': 'In',
  'DDD': 'In',
  'Total2': 'In'},
 'Mln': {'AAA': '$-1,707',
  'BBB': ',200',
  'Total1': '$-507',
  'CCC': '5',
  'DDD': ',353',
  'Total2': ',598'},
 'US$ Mln': {'AAA': '$-258',
  'BBB': '1',
  'Total1': '$-77',
  'CCC': '',
  'DDD': '5',
  'Total2': '6'}}

有人可以告诉我如何编写代码吗?

你必须按照.loc使用pd.IndexSlice

像这样。

idx = pd.IndexSlice[['Total1', 'Total2'], :]
# If you don't want to hard-code use this
idx = pd.IndexSlice[df.index[[2, 5]], :]

根据需要制作样式功能。

# 1
def make_bold(val):
    return 'font-weight: bold'
# For italic use 'font-style: italic'
# 2
def apply_color(s):
    if s.isin(['In']).any():
        return ['color: green' for val in s]
    return ['color: red' for val in s]

你使用 df.style.applymap for element wise, df.style.apply column/row 明智。

s = df.style.applymap(
    make_bold, subset=pd.IndexSlice[["Total1", "Total2"], :] # subset=idx
).apply(apply_color, axis=1)
s

输出:


对于#3

不能indexcolumns上应用样式 同样根据 pandas style-docs,在 Limitations 部分,

You can only style the values, not the index or columns

让我们尝试 applyaxis=1:

df.style.apply(lambda x: ['color:red' if x['In / Out']=='Out' 
                           else 'color:green']*len(x), axis=1)

输出:

df.style.apply(lambda x: ['color:red' if x['In / Out']=='Out'
else 'color:green']*len(x), axis=1)