gpt4 book ai didi

python - Pandas 数据帧 : Remove row satisfying certain condition

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:28 25 4
gpt4 key购买 nike

我有一个名为 df 的 Pandas DataFrame,其中包含一个名为 _text 的列。我想删除 _text 中的值不是字符串的所有行。

最初我是这样做的:

df['_text'] = df['_text'].apply(lambda t: t if isinstance(t, basestring) else '')

但这只是将其设置为空字符串。

如何删除 _text 列中的值不是字符串的任何行?

谢谢!

最佳答案

你已经很接近了,只需要从 apply 返回 bool 掩码,然后使用 boolean indexing返回所有字符串值(因此删除所有非字符串,如数字):

df[df['_text'].apply(lambda t: isinstance(t, basestring))]

或者:

df[df['_text'].apply(type) == basestring]

示例:

df= pd.DataFrame({'_text':[1,4,'ss','']})
print (df)
_text
0 1
1 4
2 ss
3

print (df['_text'].apply(lambda t: isinstance(t, basestring)))
0 False
1 False
2 True
3 True
Name: _text, dtype: bool

#for python 3 it return str, for python 2 basestring
print (df['_text'].apply(type))
0 <class 'int'>
1 <class 'int'>
2 <class 'str'>
3 <class 'str'>
Name: _text, dtype: object

df1 = df[df['_text'].apply(lambda t: isinstance(t, basestring))]
print (df1)
_text
2 ss
3

df1 = df[df['_text'].apply(type) == basestring]
print (df1)
_text
2 ss
3

关于python - Pandas 数据帧 : Remove row satisfying certain condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45237083/

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