Pandas样式:条件格式

2024-03-29 11:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我将对熊猫数据帧应用以下格式

数据如下:

{'In / Out': {'AAA': 'Out',
  'BBB': 'In',
  'Total1': 'Out',
  'CCC': 'In',
  'DDD': 'In',
  'Total2': 'In'},
 'Mln': {'AAA': '$-1,707',
  'BBB': '$1,200',
  'Total1': '$-507',
  'CCC': '$245',
  'DDD': '$1,353',
  'Total2': '$1,598'},
 'US$ Mln': {'AAA': '$-258',
  'BBB': '$181',
  'Total1': '$-77',
  'CCC': '$32',
  'DDD': '$175',
  'Total2': '$206'}}

  • 首先,我想把整个第三排和第六排都加粗。我已经犯了一个错误
  • 第二,当第二列==输入时,我希望第二、第三和第四列为绿色,如果第二列==输出,则第二、第三和第四列为红色。我该怎么做
  • 第三,我只希望文本“Total1”和“Total2”(不是整个列)右对齐,同一列中的其他文本可以保持左对齐

有人能告诉我怎么编码吗


Tags: 数据in文本格式错误outusbbb
2条回答

让我们试试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)

您必须按照.loc使用^{}

像这样

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]

在元素方面使用^{},在列/行方面使用^{}

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

输出:

enter image description here


对于#3

您不能在indexcolumns上应用样式 另请参见^{},在限制部分

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

相关问题 更多 >