Python 多索引列样式器
版本:Python 3.7.6、1.0.0 输入数据帧Python 多索引列样式器,python,pandas,Python,Pandas,版本:Python 3.7.6、1.0.0 输入数据帧 df = pd.DataFrame(dict( recruit_dt=["1/1/2017"]*3+["1/1/2018"]*3+["1/1/2019"]*3, label = [1,3,4]*3, nmem = np.random.choice(list(range(10000,3000000)),9), pct_fem = np.random.sample(9), mean_age = 50 +
df = pd.DataFrame(dict(
recruit_dt=["1/1/2017"]*3+["1/1/2018"]*3+["1/1/2019"]*3,
label = [1,3,4]*3,
nmem = np.random.choice(list(range(10000,3000000)),9),
pct_fem = np.random.sample(9),
mean_age = 50 + 10*np.random.sample(9),
sd_age = 8 + 2*np.random.sample(9)
))
希望在以下转换之后呈现此内容
dfp = pd.pivot_table(df, values=["nmem","pct_fem","mean_age","sd_age"], index="recruit_dt", columns="label")
dfp = dfp.reindex(columns=['nmem', 'pct_fem', 'mean_age', 'sd_age'], level=0)
如何编写样式器,使所有nmem列都有千个分隔符{:,},'pct_fem'是小数点后两位的百分比,mean_age和sd_age是小数点后两位的浮点数?是否有一种方法将styler.format或styler.apply与indexlice一起使用
==
编辑:这似乎有效。有更简洁的解决方案吗
dfp.columns.names = ["metrics","label"]
dfp.style.format("{:,}", subset=pd.IndexSlice[:,'nmem']) \
.format("{:.2%}", subset=pd.IndexSlice[:,'pct_fem']) \
.format("{:.2f}", subset=pd.IndexSlice[:,['mean_age','sd_age']])
可以使用列表来指定子集参数的参数,以选择相关列
>>> (dfp
.style
.format('{:.0f}', na_rep='-', subset=[col for col in dfp.columns if col[0] == 'nmen'])
.format('{:.2%}', na_rep='-', subset=[col for col in dfp.columns if col[0] == 'pct_fem'])
.format('{:,.2f}', na_rep='-', subset=[col for col in dfp.columns if col[0] in {'mean_age', 'sd_age'}])
)
一个更普遍的解决方案:
# Styles.
pct_two = '{:.2%}'
comma_float = '{:.0f}'
comma_float_2 = '{:.2f}'
# Styling to be applied to specified columns.
formats = {
'nmean': comma_float,
'pct_fem': pct_two,
'mean_age': comma_float_2,
'sd_age': comma_float_2,
}
# Create dictionary of multi-index columns with specified styling.
format_dict = {
midx: formats[level_val]
for level_val in formats
for midx in [col for col in dfp if col[0] == level_val]
}
# Apply styling to dataframe.
dfp.style.format(format_dict)
可以使用列表来指定子集参数的参数,以选择相关列
>>> (dfp
.style
.format('{:.0f}', na_rep='-', subset=[col for col in dfp.columns if col[0] == 'nmen'])
.format('{:.2%}', na_rep='-', subset=[col for col in dfp.columns if col[0] == 'pct_fem'])
.format('{:,.2f}', na_rep='-', subset=[col for col in dfp.columns if col[0] in {'mean_age', 'sd_age'}])
)
一个更普遍的解决方案:
# Styles.
pct_two = '{:.2%}'
comma_float = '{:.0f}'
comma_float_2 = '{:.2f}'
# Styling to be applied to specified columns.
formats = {
'nmean': comma_float,
'pct_fem': pct_two,
'mean_age': comma_float_2,
'sd_age': comma_float_2,
}
# Create dictionary of multi-index columns with specified styling.
format_dict = {
midx: formats[level_val]
for level_val in formats
for midx in [col for col in dfp if col[0] == level_val]
}
# Apply styling to dataframe.
dfp.style.format(format_dict)
让我们试试这个:
idx = pd.IndexSlice
formatter_dict = {i:"{:,}" for i in dfp.loc[:, idx['nmem', :]].columns}
formatter_dict2 = {i:"{:.2%}" for i in dfp.loc[:, idx['pct_fem', :]].columns}
formatter_dict3 = {i:"{:.2f}" for i in dfp.loc[:, idx[['mean_age', 'sd_age'], :]].columns}
formatter_dict.update(formatter_dict2)
formatter_dict.update(formatter_dict3)
dfp.style.format(formatter_dict)
输出:
让我们试试这个:
idx = pd.IndexSlice
formatter_dict = {i:"{:,}" for i in dfp.loc[:, idx['nmem', :]].columns}
formatter_dict2 = {i:"{:.2%}" for i in dfp.loc[:, idx['pct_fem', :]].columns}
formatter_dict3 = {i:"{:.2f}" for i in dfp.loc[:, idx[['mean_age', 'sd_age'], :]].columns}
formatter_dict.update(formatter_dict2)
formatter_dict.update(formatter_dict3)
dfp.style.format(formatter_dict)
输出:
您的编辑是正确的。就我所知,在使用pd.indexlice时使用它似乎是最好的解决方案。请将此作为答案发布。对我来说,这段代码既不会改变安卓1.0.1版的原始格式,也不会改变Windows10 1.2.3版的原始格式!您的编辑是正确的。就我所知,在使用pd.indexlice时使用它似乎是最好的解决方案。请将此作为答案发布。对我来说,这段代码既不会改变安卓1.0.1版的原始格式,也不会改变Windows10 1.2.3版的原始格式!对我来说,这段代码既不会改变安卓1.0.1版熊猫版的原始格式,也不会改变Windows10 1.2.3版熊猫版的原始格式!对我来说,这段代码既不会改变安卓1.0.1版熊猫版的原始格式,也不会改变Windows10 1.2.3版熊猫版的原始格式!