【问题标题】:creating a numpy array of mixed data type创建一个混合数据类型的numpy数组
【发布时间】:2021-06-10 10:22:18
【问题描述】:

例如,我有三个字典:

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。

【问题讨论】:

    标签: python-3.x dictionary numpy-ndarray


    【解决方案1】:

    您可以通过将 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]
    

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 2020-08-04
      • 2014-09-10
      • 2020-01-05
      • 2017-06-21
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多