如何在不丢失样式的情况下替换列值?

问题描述 投票:0回答:1

这是我的样式数据框:

Style Dataframe

我想要的是将

aEV
的值更改为
aEV_percentile
,但不丢失样式,或者更具体地说,不丢失
aEV_percentile
的背景颜色。这是我的凌乱代码:

gradient = matplotlib.colors.LinearSegmentedColormap.from_list("", ['blue', 'white', '#f81707'])

data_style = players_data_df.style.format(mapper)
.background_gradient(subset=['aEV'], cmap=gradient,
vmin=players_data_df.aEV.min(),
vmax=players_data_df.aEV.max())

data_style = data_style
.background_gradient(subset=['aEV_percentile'], cmap=gradient,
vmin=players_data_df.aEV_percentile.min(),
vmax=players_data_df.aEV_percentile.max())

我试过这个:

data_style.data['aEV_percentile'] = data_style.data['aEV']

但是

aEV_percentile
失去了它的风格。它完全是
aEV
风格

也许这是不可能的。我想这样做是因为我觉得 aEV_percentile 渐变颜色更能代表百分位数。

python pandas dataframe matplotlib google-colaboratory
1个回答
0
投票

事实上,您只需要复制数据框并使用旧数据框的值将样式应用到新数据框。我刚刚添加了一个最小的可复制数据框:

import pandas as pd
import matplotlib

aEV = [95.8, 94.0, 93.9, 92.5, 91.8, 91.5, 90.9, 90.3, 89.3, 89.1, 88.8, 87.8]
aEV_percentile = [100, 98, 96, 94, 92, 90, 88, 85, 83, 81, 79, 77]

df = pd.DataFrame({'aEV': aEV, 'aEV_percentile': aEV_percentile})

new_df = df.copy()
gradient = matplotlib.colors.LinearSegmentedColormap.from_list("", ['blue', 'white', '#f81707'])
data_style = new_df.style.background_gradient(subset=['aEV'], cmap=gradient,
                                                       vmin=df.aEV.min(),
                                                       vmax=df.aEV.max())

new_df['aEV_percentile'] = new_df['aEV']
data_style = data_style.background_gradient(subset=['aEV_percentile'], cmap=gradient,
                                            vmin=df.aEV_percentile.min(),
                                            vmax=df.aEV_percentile.max())

data_style

此代码的结果如下:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.