在pandas系列对象中查找非整数值

时间:2016-03-29 08:33:31

标签: python-3.x pandas

如何在pandas系列对象中找到像float,string这样的非整数值?

有一个像这样的系列对象,

a=(1.2,3,4,5,6,2,8,5,9) 

我尝试了to_numeric,但这无助于识别float值。有没有办法检查integer值?

2 个答案:

答案 0 :(得分:0)

如果list comprehension的值为typestring,则可以使用integer来检查非整数值:

import pandas as pd

a=['a',3,4,5,6,2,8,5,9]

s = pd.Series(a)
print s
0    a
1    3
2    4
3    5
4    6
5    2
6    8
7    5
8    9
dtype: object

print [type(x) for x in s]
[<type 'str'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>, <type 'int'>]

print [type(x) == int for x in s]
[False, True, True, True, True, True, True, True, True]

to_numericnotnull

print pd.to_numeric(s, errors='coerce').notnull()
0    False
1     True
2     True
3     True
4     True
5     True
6     True
7     True
8     True
dtype: bool

如果值为intfloat,则Series会将所有值转换为float

import pandas as pd

a=[1.2,3,4,5,6,2,8,5,9]

s = pd.Series(a)
print s
0    1.2
1    3.0
2    4.0
3    5.0
4    6.0
5    2.0
6    8.0
7    5.0
8    9.0
dtype: float64

print [type(x) for x in s]
[<type 'numpy.float64'>, <type 'numpy.float64'>, <type 'numpy.float64'>, <type 'numpy.float64'>, <type 'numpy.float64'>, <type 'numpy.float64'>, <type 'numpy.float64'>, <type 'numpy.float64'>, <type 'numpy.float64'>]

答案 1 :(得分:0)

分隔整数和浮点数的一种天真的解决方案是将浮点数与其舍入值进行比较:

import pandas as pd
a = (1.2,3,4,5,6,2,8,5,9)
df_floats = pd.to_numeric(a)
df_rounds = df_floats.round()
df_ints = df_rounds[df_rounds == df_floats].astype(int)
df_floats = df_floats[df_rounds != df_floats]