鉴于Series喜欢
import pandas as pd
s = pd.Series(['foo', 'bar', 42])
Run Code Online (Sandbox Code Playgroud)
我想获得一个"子系列" pd.Series(['foo', 'bar']),其中所有值都是字符串.我试过像这样的布尔索引:
s[isinstance(s, str)]
Run Code Online (Sandbox Code Playgroud)
但这给了一个
KeyError:错误
到目前为止,在我搜索合适的方法时,我遇到了select,但这会在标签上强加一个标准,而不是值.在这种情况下,如何根据值(类型)进行过滤?
jez*_*ael 14
使用apply或列出理解:
s[s.apply(lambda x: isinstance(x, str))]
Run Code Online (Sandbox Code Playgroud)
同样,谢谢Jon Clements?:
s[s.apply(isinstance, args=(str,))]
Run Code Online (Sandbox Code Playgroud)
s[[isinstance(x, str) for x in s]]
Run Code Online (Sandbox Code Playgroud)
全部回报:
0 foo
1 bar
dtype: object
Run Code Online (Sandbox Code Playgroud)
编辑:
不建议这样做,谢谢cᴏʟᴅsᴘᴇᴇᴅ:
s[s.apply(type) == str]
Run Code Online (Sandbox Code Playgroud)
一个小技巧pd.to_numeric:
s[pd.to_numeric(s, errors='coerce').isnull()]
0 foo
1 bar
dtype: object
Run Code Online (Sandbox Code Playgroud)
如果某个项目是数字,则它会被成功强制(而不是NaN),因此会从最终结果中删除。