在pandas series对象中查找非整数值

4

如何在pandas系列对象中查找非整数值,例如浮点数、字符串?

有一个类似于以下的系列对象:

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

我尝试使用to_numeric,但这并不能帮助识别float值。有没有一种方法可以检查integer值?


1
你可以使用 a.apply(lambda x : isinstance(x, int)) 或类似的方法,但是对于大量数据来说,这样做会很慢。 - EdChum
2个回答

1
一个分离整数和浮点数的天真解决方案是将浮点数与其四舍五入后的值进行比较:
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]

1

如果要检查非整数值,可以使用列表推导式,如果值的类型字符串整数

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

如果值是 intfloatSeries 将所有值转换为 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'>]

感谢您的回复。我正在读取对象数据类型的数据帧。因此,该列在系列中显示为字符串。我还想将浮点型数据分开处理。 - sumi1234
如果您将Series读取为字符串,则需要将其转换为数字。如果至少有一个浮点值,则会自动转换为float。或者我漏掉了什么? - jezrael
这很有用。我还想将整数和浮点值分别放入两个不同的列表中。 - sumi1234
我认为将整数和浮点数分开是个问题。你能把整数和浮点数的序列加在一起吗?因为我尝试了但没有成功。 - jezrael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接