本文介绍了如何选择哪个多索引轴将groupby对象中的数据拆分到不同的子图中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用一个pandas.groupby
对象,该对象已对其应用了这样的功能:
I'm working with a pandas.groupby
object to which I have applied a function as such:
x = data.groupby(['congruent', 'contrast']).apply(lambda s: s.mean())[['cresp1', 'cresp2']]
print x
的输出:
cresp1 cresp2
congruent contrast
False 1.0 0.423077 0.442308
2.0 0.537037 0.481481
2.5 0.576923 0.634615
3.0 0.568182 0.500000
3.5 0.675000 0.750000
4.0 0.687500 0.604167
5.0 0.687500 0.875000
10.0 0.869565 0.913043
True 1.0 0.568182 0.386364
2.0 0.547619 0.500000
2.5 0.522727 0.477273
3.0 0.557692 0.634615
3.5 0.571429 0.928571
4.0 0.770833 0.937500
5.0 0.791667 0.937500
10.0 0.820000 0.920000
我想将这些数据绘制成两个不同的子图,一个用于congruent == False
的所有值,另一个用于congruent == True
的所有值.
I would like to plot these data into two distinct subplots, one for all values where congruent == False
and the other for all values where congruent == True
.
我尝试做x.plot(subplots=True)
,但这会为每个列创建一个子图(即cresp1
与cresp2
),这是我想要的不是:
I tried doing x.plot(subplots=True)
, but this creates a subplot for each column (i.e. cresp1
vs cresp2
), which is not what I want:
我该怎么做?
推荐答案
您可以自己绘制:
import pylab as pl
import io
import pandas as pd
txt = """congruent contrast cresp1 cresp2
False 1.0 0.423077 0.442308
2.0 0.537037 0.481481
2.5 0.576923 0.634615
3.0 0.568182 0.500000
3.5 0.675000 0.750000
4.0 0.687500 0.604167
5.0 0.687500 0.875000
10.0 0.869565 0.913043
True 1.0 0.568182 0.386364
2.0 0.547619 0.500000
2.5 0.522727 0.477273
3.0 0.557692 0.634615
3.5 0.571429 0.928571
4.0 0.770833 0.937500
5.0 0.791667 0.937500
10.0 0.820000 0.920000"""
df = pd.read_csv(io.BytesIO(txt), delim_whitespace=True).ffill()
df = df.set_index(["congruent","contrast"])
levels = df.index.levels[0]
fig, axes = pl.subplots(len(levels))
for level, ax in zip(levels, axes):
df.loc[level].plot(ax=ax, title=str(level))
输出:
这篇关于如何选择哪个多索引轴将groupby对象中的数据拆分到不同的子图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!