例如我有三本词典:
first_dictionary = {'Feature1': array([0, 0, 1, 0]),
'Feature2': array([0, 1, 0, 0]),
'Feature3': array([1, 0, 0])}
second_dictionary = { 'Feature4': array([0., 1.]),
'Feature5': array([0.]),
'Feature6': array([0., 1.])}
third_dictionary = {{'Feature7': array([ 0., 0., 0., 912., 0.,
0., 0., 0., 0., 0.]),
'Feature8': array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])}
真正的词典有更多的键(每个约 50 个)。我结合了 numpy 数组来生成一个 1D numpy 数组:
output = []
for dictionary in [first_dictionary,second_dictionary,third_dictionary]:
for key, value in dictionary.items():
output += list(value)
output_array = np.array(output)
但是,当我这样做时,数据类型都被弄乱了,因为我想生成一个最终的 numpy 数组,它保持原始 numpy 数组的数据类型。
所以我得到的是:
array([ 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0.,
0., 1., 0., 0., 1., 0., 0., 0., 912., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0.])
鉴于你可以,你的第一本字典只有整数,所以我希望它看起来像:
array([ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,
0., 1., 0., 0., 1., 0., 0., 0., 912., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0.])
我怎样才能做到这一点?见解将不胜感激。 旁注:所有字典中的所有 numpy 数组都是使用 np.ndarray 创建的,类型设置为 None。
您可以通过将 numpy 数组的 dtype 设置为
object
来做到这一点
output_array = np.array(output, dtype= object)
[0 0 1 0 0 1 0 0 1 0 0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 0.0 912.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0]