我有一个多数据类型的系列pd.Series
,比如[100, 50, 0, foo, bar, baz]
当我运行 pd.Series.str.isnumeric()
我得到 [NaN, NaN, NaN, False, False, False]
为什么会这样?它不应该为本系列的前三个返回 True
吗?
最佳答案
Pandas 字符串方法紧跟 Python 方法:
str.isnumeric(100) # TypeError
str.isnumeric('100') # True
str.isnumeric('a10') # False
任何产生错误的类型都会给出 NaN
。根据 Python docs , str.isnumeric
只适用于字符串:
str.isnumeric()
Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise.
根据 Pandas docs , pd.Series.str.isnumeric
等价于str.isnumeric
:
Series.str.isnumeric()
Check whether all characters in each string in the Series/Index are numeric. Equivalent tostr.isnumeric()
.
你的系列有“object”数据类型,这是一个包罗万象的类型,它包含指向任意 Python 对象的指针。这些可能是字符串、整数等的混合。因此,您应该期望 NaN
值未找到字符串。
为了适应数字类型,您需要显式转换为字符串,例如给定一系列 s
:
s.astype(str).str.isnumeric()
关于python - Pandas str.isnumeric() 的预期行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51598770/