如何在Pandas数据框中选择基于行的类别 [英] How to select rows based categories in Pandas dataframe

查看:73
本文介绍了如何在Pandas数据框中选择基于行的类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真的很琐碎,但不敢相信我已经徘徊了一个小时,仍然可以找到答案,所以您在这里:

this is really trivial but can't believe I have wandered around for an hour and still can find the answer, so here you are:

    df = pd.DataFrame({"cats":["a","b"], "vals":[1,2]})
    df.cats = df.cats.astype("category")
    df

我的问题是如何选择其猫"列类别为"a"的行.我知道df.loc[df.cats == "a"]可以工作,但是它基于元素上的相等性.有没有一种基于类别级别进行选择的方法?

My problem is how to select the row that its "cats" columns's category is "a". I know that df.loc[df.cats == "a"] will work but it's based on equality on element. Is there a way to select based on levels of category?

推荐答案

这有效:

df.cats[df.cats=='a']

更新

问题已更新.新解决方案:

The question was updated. New solution:

df[df.cats.cat.categories == ['a']]

这篇关于如何在Pandas数据框中选择基于行的类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆