pandas 检查熊猫数据框列中的值是否为整数,如果不是则将其写入列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56243441/
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 06:23:20  来源:igfitidea点击:

Check if values in pandas dataframe column is integer and write it to a list if not

pythonpandasinteger

提问by Padfoot13288

I have a pandas dataframe with a column which could have integers, float, string etc. I would like to iterate over all the rows and check if each value is integer and if not, I would like to create a list with error values (values that are not integer)

我有一个 Pandas 数据框,其中有一列可以包含整数、浮点数、字符串等。我想遍历所有行并检查每个值是否为整数,如果不是,我想创建一个包含错误值(值)的列表不是整数)

I have tried isnumeric(), but couldnt iterate over each row and write errors to output. I tried using iterrows() but it converts all values to float.

我尝试过 isnumeric(),但无法遍历每一行并将错误写入输出。我尝试使用 iterrows() 但它将所有值转换为浮点数。

ID     Field1
1      1.15
2      2
3      1
4      25
5      and

Expected Result:

预期结果:

[1.15,"and"]

回答by cs95

If "Field1" is a column of strings, use str.isdigit(returns True for integers only) and negate:

如果“Field1”是一列字符串,则使用str.isdigit(仅对整数返回 True)并否定:

df.loc[~df['Field1'].str.isdigit(), 'Field1'].tolist()
# ['1.15', 'and']

Alternatively, if the column contains mixed types, use

或者,如果列包含混合类型,请使用

df.loc[~df['Field1'].astype(str).str.isdigit(), 'Field1'].tolist()
# [1.15, 'and']