英文:
How to style a pandas pivot table dataframe?
问题
I understand your request. Here is the translated code portion:
我创建了一个数据透视表的数据框,我想要对其进行自定义样式设置。我想要遍历每一行和列的数值,并比较当前数值与前一列的数值。如果当前数值大于前一列的数值,将背景颜色设置为`'lightgreen'`。如果当前数值小于前一列的数值,将背景颜色设置为`'lightcoral'`。请参考下面的图片查看数据透视表的数据框。
```python
df.columns
Index(['AUG-2022', 'SEP-2022', 'OCT-2022', 'NOV-2022', 'DEC-2022', 'JAN-2023'], dtype='object')
我尝试了下面的代码来创建一个样式,但是我一直在得到以下错误。
styler = df.style
# 遍历数据框的每一行
for i, row in enumerate(df.values):
# 遍历每一行的每一列
for j in range(1, len(row)):
# 比较当前值和前一个值
if row[j] < row[j-1]:
# 将背景颜色设置为浅红色
styler.set_properties(subset=[(i, j)], **{'background-color': 'lightcoral'})
elif row[j] > row[j-1]:
# 将背景颜色设置为浅绿色
styler.set_properties(subset=[(i, j)], **{'background-color': 'lightgreen'})
styler
报错信息:raise KeyError(f"None of [{key}] are in the [{axis_name}]")
我想要了解我做错了什么,以及如何修复这个问题。感谢您的帮助!
英文:
I have created a pivot table dataframe and I want to add custom styling to it. I want to iterate over each row and column values and compare the data value from the previous column value. If the value is greater than the previous column value, change the background color to 'lightgreen'
. If the column value is less than the previous column value, change the background color to 'lightcoral'
. Please refer the image to take a look at the pivot table dataframe.
df.columns
Index(['AUG-2022', 'SEP-2022', 'OCT-2022', 'NOV-2022', 'DEC-2022', 'JAN-2023'], dtype='object')
I tried this code to create a styler but I have been getting this error.
styler = df.style
# iterate over each row of the DataFrame
for i, row in enumerate(df.values):
# iterate over each column of the row
for j in range(1, len(row)):
# compare current value to previous value
if row[j] < row[j-1]:
# # set background color to light red
styler.set_properties(subset=[(i, j)], **{'background-color': 'lightcoral'})
elif row[j] > row[j-1]:
# # set background color to light green
styler.set_properties(subset=[(i, j)], **{'background-color': 'lightgreen'})
styler
> raise KeyError(f"None of [{key}] are in the [{axis_name}]")
I want to understand what am I doing wrong and how can I fix this.
Your help is appreciated!
答案1
得分: 0
以下是您要翻译的代码部分:
def color(df):
conds = [
df.gt(df.shift(+1, axis=1)), # 当前列是否大于前一列?
df.lt(df.shift(+1, axis=1)), # 当前列是否小于前一列?
]
vals = [
"background-color: lightgreen",
"background-color: lightcoral",
]
return pd.DataFrame(np.select(conds, vals, default=""),
index=df.index, columns=df.columns)
df.style.apply(color, axis=None)
希望这对您有所帮助!
英文:
You can try this :
def color(df):
conds = [
df.gt(df.shift(+1, axis=1)), #is the current column greater than the previous ?
df.lt(df.shift(+1, axis=1)), #is the current column lower than the previous ?
]
vals = [
"background-color: lightgreen",
"background-color: lightcoral",
]
return pd.DataFrame(np.select(conds, vals, default=""),
index=df.index, columns=df.columns)
df.style.apply(color, axis=None)
Output :
Input used :
ms = pd.date_range(start="2023-01-01", end="2023-12-01", freq="MS").strftime("%b-%Y")
index = pd.Index([f"COMPANY_{i}" for i in range(1, 11)], name="COMPANY NAME")
columns = [m.upper() for m in ms]
df = pd.DataFrame(
data=np.random.randint(low=0, high=10000, size=(len(index), len(columns))),
index=index, columns=columns
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论