gpt4 book ai didi

python - Pandas 系列中的字符串过滤器

转载 作者:行者123 更新时间:2023-11-28 21:35:23 24 4
gpt4 key购买 nike

还有比这更好的方法来过滤 Pandas 系列中的字符串吗?

这是我想到的:

df = pd.DataFrame({'a': [1,2,3,4,'cat','hat','mat'], 'b': [1,2,3,4,5,6,7] })

原文:

a   b
0 1 1
1 2 2
2 3 3
3 4 4
4 cat 5
5 hat 6
6 mat 7

df = df[df['a'].apply(lambda x: isinstance(x, str))]

结果:

a   b
4 cat 5
5 hat 6
6 mat 7

但是,这种语法似乎很冗长。有形式的东西吗? :

df[df['a'].is_type(str)] 

编辑:我感兴趣的是检查类型,而不是内容。因此,例如,我想包含 '12345' 并排除 12345

最佳答案

我会推荐to_numeric

df[pd.to_numeric(df.a,errors='coerce').isna()]
Out[246]:
a b
4 cat 5
5 hat 6
6 mat 7

如果你把评论中提到的情况考虑为零

df[df.a.map(lambda x : type(x).__name__)=='str']
Out[257]:
a b
4 cat 5
5 hat 6
6 mat 7

关于python - Pandas 系列中的字符串过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com