[英]Convert numpy elements to numpy dtypes
是否有一種簡便的方法可以將numpy數組的元素從任意和未知的本機python類型轉換為等效的numpy類型? 我可以檢查每個元素的類型並分別轉換每種類型,但是我希望可以有一個更方便的方法。
我通過在舊數組中提取每個對象的屬性來在新數組中獲得python類型,如下所示:
import numpy as np
from operator import attrgetter
class myobj():
def __init__(self, value):
self.myattr = value
obj_array = np.empty((3,3), dtype='object')
for i in range(obj_array.shape[0]):
for j in range(obj_array.shape[0]):
obj_array[i,j] = myobj(i+j)
native_type_array = np.frompyfunc(attrgetter('myattr'), 1, 1)(obj_array)
根據這個問題/答案。
您可以使用numpy例程astype()
:
>>> import numpy as np
>>> arr = np.array([1.2, 3.4, 5.6])
>>> arr = arr.astype(np.int)
>>> print(arr)
[1 2 3]
這些值存儲在myattr
屬性中,因此我認為您需要明確指定此屬性。 這應該工作
new_obj_array = np.frompyfunc(lambda x : np.int32(x.myattr), 1, 1)(obj_array)
如果我在您的代碼中添加__repr__
方法並顯示以下內容:
import numpy as np
from operator import attrgetter
class myobj():
def __init__(self, value):
self.myattr = value
def __repr__(self):
return self.myattr.__repr__()
obj_array = np.empty((3,3), dtype='object')
for i in range(obj_array.shape[0]):
for j in range(obj_array.shape[0]):
obj_array[i,j] = myobj(i+j)
native_type_array = np.frompyfunc(attrgetter('myattr'), 1, 1)(obj_array)
print(native_type_array.shape)
print(native_type_array.dtype)
print(native_type_array)
print(obj_array)
我懂了
1011:~/mypy$ python3 stack38332556.py
(3, 3)
object
[[0 1 2]
[1 2 3]
[2 3 4]]
[[0 1 2]
[1 2 3]
[2 3 4]]
native_type_array
也是一個對象dtype數組-這是frompyfunc
的文檔所說的。 但是由於元素是數字,所以顯示看起來不錯。
通過給myobj
類似的repr
,我得到了同樣的東西。 如果我更改代表
def __repr__(self):
return '<%s>'%self.myattr
我得到:
[[<0> <1> <2>]
[<1> <2> <3>]
[<2> <3> <4>]]
這也適用於列表。 print([myobj(10),myobj(11)])
產生[<10>, <11>]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.