python - Pandas str.isnumeric() 的预期行为

标签 python string pandas

我有一个多数据类型的系列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 to str.isnumeric().

你的系列有“object”数据类型,这是一个包罗万象的类型,它包含指向任意 Python 对象的指针。这些可能是字符串、整数等的混合。因此,您应该期望 NaN 值未找到字符串。

为了适应数字类型,您需要显式转换为字符串,例如给定一系列 s:

s.astype(str).str.isnumeric()

关于python - Pandas str.isnumeric() 的预期行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51598770/

相关文章:

python - 计算文本中的字母数

python - pysvn 是否允许您以相反的顺序限制日志消息?

java - 保留大写/小写字符和空格的正则表达式?

python - Pandas Python 中的组合

python - Pandas 读取后删除CSV文件中的行

python - 尝试更改 pandas 数据帧中的索引值时出错(IndexError : too many indices for array)

python - Keras:如何加载具有两个输出和自定义损失函数的模型?

python - Pandas 更新多索引数据框中的值

c - C 中的 ispunct() 有异常(exception)吗?

c - 如何通过正则表达式从名称=值格式的字符串中提取名称