Pandas的预期行为str.is数字()

2024-05-15 17:02:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个多数据类型系列pd.Series,就像[100, 50, 0, foo, bar, baz]

当我运行pd.Series.str.isnumeric()

我得到[NaN, NaN, NaN, False, False, False]

为什么会这样?它不应该为本系列的前三个返回True?在


Tags: falsetruefoobarbaznanseriespd
2条回答

Pandas字符串方法紧跟Python方法:

str.isnumeric(100)    # TypeError
str.isnumeric('100')  # True
str.isnumeric('a10')  # False

任何产生错误的类型都将给出NaN。根据Pythondocsstr.isnumeric仅适用于字符串:

str.isnumeric()
Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise.

根据熊猫docspd.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

^{pr2}$

使用字符串访问器将您的数字转换为NaN,它在您尝试使用isnumeric之前发生:

s = pd.Series([100, 50, 0, 'foo', 'bar', 'baz'])
s.str[:]

0    NaN
1    NaN
2    NaN
3    foo
4    bar
5    baz
dtype: object

因此,使用isnumeric时,NaN仍然存在。请先使用astype

^{pr2}$

相关问题 更多 >