我刚开始使用python进行数据可视化。我搜索过google& stackoverflow但无法找到我的问题的答案。希望你能提供帮助:
我有一个pandas df,每人有几个数据行(id),另外两个名为StimCat的列(3个级别:A,B,C)& rt(连续值,反应时间),例如像这样:
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。
有关如何做到这一点的任何提示?或者如果之前已经问过这个问题(我还没有找到),你可以指望我参加相应的参赛作品吗?谢谢大家!!!!我真的很感激!
答案 0 :(得分:1)
如果您不打算绘制它,请不要计算它。使用query
/布尔索引/ eval
/ isin
并将其过滤掉。
fig, ax = plt.subplots(figsize=(15,7))
df.query('StimCat != "C"')\
.groupby(['id','StimCat'])\
.mean()['rt']\
.unstack()\
.plot.bar(ax=ax)
如果你的目标是排除多个这样的类别,请尝试这样的事情 -
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
。