如何为 pandas 数据透视表 DataFrame 添加样式?

huangapple go评论68阅读模式
英文:

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 &#39;lightgreen&#39;. If the column value is less than the previous column value, change the background color to &#39;lightcoral&#39;. Please refer the image to take a look at the pivot table dataframe.如何为 pandas 数据透视表 DataFrame 添加样式?

df.columns

Index([&#39;AUG-2022&#39;, &#39;SEP-2022&#39;, &#39;OCT-2022&#39;, &#39;NOV-2022&#39;, &#39;DEC-2022&#39;, &#39;JAN-2023&#39;], dtype=&#39;object&#39;)

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] &lt; row[j-1]:
#             # set background color to light red
            styler.set_properties(subset=[(i, j)], **{&#39;background-color&#39;: &#39;lightcoral&#39;})
        elif row[j] &gt; row[j-1]:
#             # set background color to light green
            styler.set_properties(subset=[(i, j)], **{&#39;background-color&#39;: &#39;lightgreen&#39;})

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 = [
        &quot;background-color: lightgreen&quot;,
        &quot;background-color: lightcoral&quot;,
    ]
    return pd.DataFrame(np.select(conds, vals, default=&quot;&quot;),
                        index=df.index, columns=df.columns)

df.style.apply(color, axis=None)

Output :

如何为 pandas 数据透视表 DataFrame 添加样式?

Input used :

ms = pd.date_range(start=&quot;2023-01-01&quot;, end=&quot;2023-12-01&quot;, freq=&quot;MS&quot;).strftime(&quot;%b-%Y&quot;)

index = pd.Index([f&quot;COMPANY_{i}&quot; for i in range(1, 11)], name=&quot;COMPANY NAME&quot;)

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
)

huangapple
  • 本文由 发表于 2023年5月6日 16:54:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76187998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定