2024-05-15 17:02:28 发布
网友
我有一个多数据类型系列pd.Series,就像[100, 50, 0, foo, bar, baz]
pd.Series
[100, 50, 0, foo, bar, baz]
当我运行pd.Series.str.isnumeric()
pd.Series.str.isnumeric()
我得到[NaN, NaN, NaN, False, False, False]
[NaN, NaN, NaN, False, False, False]
为什么会这样?它不应该为本系列的前三个返回True?在
True
Pandas字符串方法紧跟Python方法:
str.isnumeric(100) # TypeError str.isnumeric('100') # True str.isnumeric('a10') # False
任何产生错误的类型都将给出NaN。根据Pythondocs,str.isnumeric仅适用于字符串:
NaN
str.isnumeric
str.isnumeric() Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise.
根据熊猫docs,pd.Series.str.isnumeric相当于str.isnumeric:
pd.Series.str.isnumeric
Series.str.isnumeric() Check whether all characters in each string in the Series/Index are numeric. Equivalent to str.isnumeric().
str.isnumeric()
您的系列有“object”数据类型,这是一个包含所有内容的类型,它包含指向任意Python对象的指针。这些值可能是字符串、整数等的混合。因此,如果找不到字符串,则应使用NaN值。在
为了适应数字类型,您需要显式地转换为字符串,例如给定一个序列s:
s
使用字符串访问器将您的数字转换为NaN,它在您尝试使用isnumeric之前发生:
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:
astype
Pandas字符串方法紧跟Python方法:
任何产生错误的类型都将给出
NaN
。根据Pythondocs,str.isnumeric
仅适用于字符串:根据熊猫docs,
pd.Series.str.isnumeric
相当于str.isnumeric
:您的系列有“object”数据类型,这是一个包含所有内容的类型,它包含指向任意Python对象的指针。这些值可能是字符串、整数等的混合。因此,如果找不到字符串,则应使用
NaN
值。在为了适应数字类型,您需要显式地转换为字符串,例如给定一个序列
^{pr2}$s
:使用字符串访问器将您的数字转换为
NaN
,它在您尝试使用isnumeric
之前发生:因此,使用
^{pr2}$isnumeric
时,NaN
仍然存在。请先使用astype
:相关问题 更多 >
编程相关推荐