从系列中删除非数值 [英] Remove non numeric values from a Series
本文介绍了从系列中删除非数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫系列,其中包含多个不同的数据类型.我想过滤掉所有非数字元素.结果系列应只包含浮点数或整数.
I have a pandas Series containing multiple different datatypes. I want to filter out all elements which are not numeric. The resulting Series should only contain floats or ints.
是否有一种简单的方法来过滤系列?我发现大多数解决方案仅适用于DataFrames.
Is there a simple way to filter the Series? Most solutions I found only worked with DataFrames.
推荐答案
更新:
In [43]: s
Out[43]:
0 0
1 1
2 str1
3 NaN
4 3
5 5
6 str2
7 4
8 NaN
dtype: object
转换为数字:
In [44]: pd.to_numeric(s, errors='coerce')
Out[44]:
0 0.0
1 1.0
2 NaN
3 NaN
4 3.0
5 5.0
6 NaN
7 4.0
8 NaN
dtype: float64
删除NaN:
In [45]: pd.to_numeric(s, errors='coerce').dropna()
Out[45]:
0 0.0
1 1.0
4 3.0
5 5.0
7 4.0
dtype: float64
这篇关于从系列中删除非数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文