請您幫我用多索引/高級索引突出顯示我的資料框中的列嗎?
我有形成表 1 的代碼:
pivot_clicks = pd.pivot_table(data=clicks, index='Источник', columns='Дата',
values=['Разница в процентах']).sort_index(axis=0, ascending=False)
pivot_clicks = pivot_clicks.swaplevel(0,1, axis=1).sort_index(axis=1, ascending=False)#.reset_index()
pivot_clicks = pivot_clicks.sort_values([pivot_clicks.columns[0]], ascending=False)
因此,(2022-02-27, 'Разница в процентах')、(2022-02-26, 'Разница в процентах') 等是 python 中此表中的列,而 'Источник' 是索引。

我想突出顯示值 >= 15 的列,并將其設為紅色。請幫幫我,因為我不能很好地處理多索引。
uj5u.com熱心網友回復:
可以使用元組訪問多索引列。例如pivot_clicks.loc[:, [("2022-02-27", 'Разница в процентах'), ("2022-02-26", 'Разница в процентах')]]
以及用于樣式化單個列的作業示例:
import pandas as pd
import numpy as np
df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
"bar", "bar", "bar", "bar"],
"B": ["one", "one", "one", "two", "two",
"one", "one", "two", "two"],
"C": ["small", "large", "large", "small",
"small", "large", "small", "small",
"large"],
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
"E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
pivot = pd.pivot_table(df, values='D', index=['C'],
columns=['A', "B"], aggfunc=np.sum)
pivot.style.applymap(lambda x: f"color: {'red' if x > 4.5 else 'black'}", subset=[("bar", "one")])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/434032.html
標籤:Python 熊猫 jupyter-笔记本 数据透视表 造型
上一篇:groupby總計/小計
下一篇:在串列中按行計算NaN值
