私は構造化numpy配列を持っています。numpyの構造化配列からPythonの 'native'値を抽出します。
numpyの構造は、タイプgoogle.protobuf.Timestamp
と一致します。
私が言った構造の各要素からseconds
int64
とnanos
int32
を抽出し、リアルTimestamp
構造に割り当てる必要があります。
以下では、誰もがテストできる便利な方法でスクリプトをリストアップします(numpy
とprotobuf
Pythonモジュールをインストールする必要があります)。
最後にTypeError
を削除して回避し、num30構造の値がTimestamp
という変数に含まれていますか?
import numpy as np
from google.protobuf import timestamp_pb2
# numpy structure that mimics google.protobuf.Timestamp
Timestamp_t = np.dtype([('seconds', np.int64), ('nanos', np.int32)])
# populate numpy array with above structure
x_values_size = 3
x_values = np.empty((x_values_size,), dtype=Timestamp_t)
x_values['seconds'] = np.linspace(0, 100, num=x_values_size, dtype=np.int64)
x_values['nanos'] = np.linspace(0, 10, num=x_values_size, dtype=np.int32)
# copy data from numpy structured array to a descriptor-created Timestamp
for elem in np.nditer(x_values) :
# destination protobuf structure (actually, part of some sequence)
# try 1: this will actually change the type of 'ts'
ts1 = timestamp_pb2.Timestamp()
print(type(ts1)) # Timestamp as expected
ts1 = elem
print(ts1) # now a numpy.ndarray
print(type(ts1))
print(ts1.dtype)
# try 2: assign member by member
ts2 = timestamp_pb2.Timestamp()
# fails with:
# TypeError: array(0, dtype=int64) has type <class 'numpy.ndarray'>, but expected one of: (<class 'int'>,)
ts2.seconds = elem['seconds']
ts2.nanos = elem['nanos']
print("-----")
免責事項:hardcore初心者は、pythonとnumpyの配列に関して言えば、
答えの短いバージョンは、値を割り当てるときに '.item()'を追加することです。私は2つの反復メソッドをタイムアウトし、 '.item()'呼び出しを追加しても、 'np.nditer'は速くなります。私はある構造から別の構造にmemberwiseを割り当てることと関連していると思います。ありがとう。 – CristiArg