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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36279233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:57:30  来源:igfitidea点击:

finding non-integer values in pandas series object

python-3.xpandas

提问by sumi1234

How to find non-integer values like float,string in pandas series object?

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

Have a series object like this,

有一个这样的系列对象,

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

I tried to_numeric, but this is not helping to identify floatvalues. Is there a way to check integervalues?

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

回答by jezrael

You can use list comprehensionfor checking non-integer values , if typeof values is stringand integer:

您可以list comprehension用于检查非整数值,如果type值是stringinteger

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]

Or by to_numericwith notnull:

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

If values are intand float, Seriesconvert all values to float:

如果值为intand float,则将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'>]

回答by Gregory Miller

A naive solution to separate ints and floats is to compare the floats with their rounded values:

分离整数和浮点数的一个简单的解决方案是将浮点数与其舍入值进行比较:

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]