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'}}
- 首先,我试图将整个第三行和第六行加粗。我已经得到一个错误。
- 其次,我希望当第二列 == In 时第二、第三和第四列为绿色,如果第二列 == Out 则为红色。我该怎么做?
- 第三,我希望只有文本'Total1'和'Total2'(不是整列)右对齐,同一列中的其他文本可以保持左对齐。
有人可以告诉我如何编写代码吗?
你必须按照.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
您不能在index
或columns
上应用样式
同样根据 pandas style-docs
,在 Limitations 部分,
You can only style the values, not the index or columns
让我们尝试 apply
和 axis=1
:
df.style.apply(lambda x: ['color:red' if x['In / Out']=='Out'
else 'color:green']*len(x), axis=1)
输出:
我将以下格式应用于 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'}}
- 首先,我试图将整个第三行和第六行加粗。我已经得到一个错误。
- 其次,我希望当第二列 == In 时第二、第三和第四列为绿色,如果第二列 == Out 则为红色。我该怎么做?
- 第三,我希望只有文本'Total1'和'Total2'(不是整列)右对齐,同一列中的其他文本可以保持左对齐。
有人可以告诉我如何编写代码吗?
你必须按照.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
您不能在index
或columns
上应用样式
同样根据 pandas style-docs
,在 Limitations 部分,
You can only style the values, not the index or columns
让我们尝试 apply
和 axis=1
:
df.style.apply(lambda x: ['color:red' if x['In / Out']=='Out'
else 'color:green']*len(x), axis=1)
输出: