Mar*_*ova 10 python styles subset multi-index pandas
我正在使用样式器格式化pandas数据框以突出显示列和格式数字.我还想应用多索引更清晰,愉快和易读.由于我将Styler应用于列的子集,因此无法使用多索引.
例:
arrays = [np.hstack([['One']*2, ['Two']*2]) , ['A', 'B', 'C', 'D']]
columns = pd.MultiIndex.from_arrays(arrays)
data = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD'))
data.columns = columns
import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)
data.style.background_gradient(cmap=cm, subset=['A'])
Run Code Online (Sandbox Code Playgroud)
有没有办法对列进行子集,以便样式器可以工作.根据以下来源,这是实现的,但没有例子,所以我很难理解如何应用它:http : //pandas.pydata.org/pandas-docs/stable/generated/pandas.formats.style. Styler.html https://github.com/pandas-dev/pandas/issues/11655
谢谢 !
Max*_*axU 11
我想你可以使用pd.IndexSlice [...]方法:
data.style.background_gradient(cmap=cm, subset=pd.IndexSlice[:, pd.IndexSlice[:, 'A']])
Run Code Online (Sandbox Code Playgroud)
演示:
In [5]: data.loc[pd.IndexSlice[:, pd.IndexSlice[:, 'A']]]
Out[5]:
One
A
0 -0.808483
1 0.009371
2 0.977138
3 -0.875554
4 -0.052424
In [6]: data
Out[6]:
One Two
A B C D
0 -0.808483 -2.280683 0.576145 0.649688
1 0.009371 0.721510 1.013764 -0.157493
2 0.977138 1.441392 1.718618 -0.320826
3 -0.875554 -1.060507 1.457075 0.570195
4 -0.052424 -0.742842 -0.203830 -1.202091
Run Code Online (Sandbox Code Playgroud)
在Jupyter:
在这里,是另一种方式:
data.style.background_gradient(cmap=cm, subset=data.columns.get_loc_level('A', level=1)[0])
Run Code Online (Sandbox Code Playgroud)
输出: