在 pandas 中,如何根据值的类型过滤系列? [英] In Pandas, how to filter a Series based on the type of the values?

查看:73
本文介绍了在 pandas 中,如何根据值的类型过滤系列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出类似Series

import pandas as pd

s = pd.Series(['foo', 'bar', 42])

我想获得一个'sub-series'pd.Series(['foo', 'bar']),其中所有值都是字符串.我已经尝试过像这样的布尔索引:

I would like to obtain a 'sub-series' pd.Series(['foo', 'bar']) in which all values are strings. I've tried Boolean indexing like so:

s[isinstance(s, str)]

但这给出了一个

KeyError:错误

KeyError: False

到目前为止,在寻找合适的方法时,我遇到了选择,但这会在标签上强加标准,而不是值.在这种情况下,如何基于值的类型进行过滤?

In my search for suitable methods so far I came across select, but this imposes a criterion on the labels, not the values. How can I filter based on (the type of) the values in this case?

推荐答案

使用apply或列表理解:

s[s.apply(lambda x: isinstance(x, str))]

与谢谢Jon Clements♦一样:

s[s.apply(isinstance, args=(str,))]


s[[isinstance(x, str) for x in s]]

所有返回:

0    foo
1    bar
dtype: object

不建议这样做,谢谢 查看全文

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