python - 防止绘制 pandas df 列的 1 个级别/值

标签 python pandas plot

我刚刚开始使用 python 进行数据可视化。我已经搜索了 google 和 stackoverflow 但无法找到我的问题的答案。希望您能够提供帮助:

我有一个 pandas df,每个人 (id) 有几个数据行,还有另外 2 个名为 StimCat 的列(3 个级别:A、B、C)和 rt(连续值、 react 时间),例如像这样:

   id  StimCat rt
0  1     A    596
1  1     B    657
2  1     C    200
3  1     C    354
4  1     A    164
5  2     A    164
6  2     B    343
7  2     B    264
8  2     A    456
9  2     C    523 
10 2     C    241

我编写了以下代码来绘制按 id 分组的每个 StimCat 级别的平均数据:

fig, ax = plt.subplots(figsize=(15,7))            
df.groupby(['id','StimCat']).mean()['rt'].unstack().plot.bar(ax=ax)

但是,实际上我只想为 StimCat 绘制 3 个级别中的 2 个,即 A 和 B,但从图中完全忽略级别 C。

关于我如何做到这一点有任何提示吗?或者,如果以前曾问过这样的问题(我还没有找到),您可以希望将我指向相应的条目吗?谢谢大家!!!!我真的很感激!

最佳答案

如果你不打算绘制它,就不要计算它。使用query/boolean indexing/eval/isin并将其过滤掉。

fig, ax = plt.subplots(figsize=(15,7)) 

df.query('StimCat != "C"')\
  .groupby(['id','StimCat'])\
  .mean()['rt']\
  .unstack()\
  .plot.bar(ax=ax)

enter image description here

如果您的目标是排除多个此类类别,请尝试这样的操作 -

cat_to_exclude = ['A', 'C'] # filter out categories A and C, for example
df = df.query('StimCat not in @cat_to_exclude')

df

   id StimCat   rt
1   1       B  657
6   2       B  343
7   2       B  264

然后执行groupby

关于python - 防止绘制 pandas df 列的 1 个级别/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48197803/

相关文章:

python - Tkinter TreeView 小部件未正确对齐/在小部件之间添加空间

Python-使用 slider 更改图形图上的文本

python - pygame.display.set_mode 窗口打开但卡住 python 3.5 mac osx 10.11.1

python - Dataframe 将 NA 值转换为 NaN

python - 如何按组计算两列值的比率?

python - Pandas:使用来自另一个数据框的值分配值

python - 在第二个或第三个大写字母后面插入空格 python

重新变换线性模型。 R 案例研究

r - 使用 savePlot 另存为 pdf 时图例被截断

python - mod_wsgi 不适用于 WAMP