0

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

数据如下:

{'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'}}

  • 首先,我试图使整个第三行和第六行加粗。我已经得到了一个错误。
  • 其次,当第二列 == In 时,我希望第二、第三和第四列为绿色,如果第二列 == Out,则为红色。我该怎么做呢 ?
  • 第三,我希望只有文本“Total1”和“Total2”(不是整个列)右对齐,同一列中的其他文本可以保持左对齐。

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

4

2 回答 2

2

你必须pd.IndexSlice按照.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]

您使用df.style.applymap元素明智,df.style.apply列/行明智。

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

输出:

在此处输入图像描述


对于#3

不能限制部分中应用样式indexcolumnspandas style-docs

您只能设置值的样式,而不是索引或列

于 2020-11-15T06:49:26.463 回答
2

apply让我们尝试axis=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)

于 2020-11-15T06:54:18.030 回答