我需要编写一个函数 F,它接受 dtype=object 的 numpy 数组,并返回数组的所有元素是否为浮点数、整数或字符串。例如:
F(np.array([1., 2.], dtype=object)) --> float
F(np.array(['1.', '2.'], dtype=object)) --> string
F(np.array([1, 2], dtype=object)) --> int
F(np.array([1, 2.], dtype=object)) --> float
F(np.array(['hello'], dtype=object)) --> string
F(np.array([1, 'hello'], dtype=object)) --> ERROR
Run Code Online (Sandbox Code Playgroud)
有什么想法可以有效地做到这一点吗?(== 使用 numpy 内置函数)
多谢
最简单的可能是运行内容np.array
并检查结果类型:
a = np.array([1., 2.], dtype=object)
b = np.array(['1.', '2.'], dtype=object)
c = np.array([1, 2], dtype=object)
d = np.array([1, 2.], dtype=object)
e = np.array(['hello'], dtype=object)
f = np.array([1, 'hello'], dtype=object)
>>> np.array(list(a)).dtype
dtype('float64')
>>> np.array(list(b)).dtype
dtype('S2')
>>> np.array(list(c)).dtype
dtype('int32')
>>> np.array(list(d)).dtype
dtype('float64')
>>> np.array(list(e)).dtype
dtype('S5')
Run Code Online (Sandbox Code Playgroud)
如果类型不兼容,它不会引发错误,因为这不是 numpy 的行为:
>>> np.array(list(f)).dtype
dtype('S5')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12219 次 |
最近记录: |