python 将元组列表转换为3d numpy数组

cidc1ykv  于 2023-04-19  发布在  Python
关注(0)|答案(3)|浏览(127)

我有一个数据集,它是一个元组列表,我需要将其转换为3d numpy数组。举个例子:

data = [(1, 65, -18, -1, -1 ),
       (1, -18,-1, -1,-1),
      (2, 65, -19, -1, -1),
      (2, 65, -18, -1, -1),
       (3, 62, -18, -1, -1)]

我想创建一个像这样的3d numpy数组:

array[[[[65], [-18], [-1], [-1]],
          [[-18], [-1], [-1], [-1]]],
          [[[65], [-19], [-1], [-1]],
          [[65], [-18], [-1], [-1]]],
          [[[62], [-18], [-1], [-1]]]]

如何使用Numpy库实现这一点?
我已经尝试过这样做:

d = defaultdict(list)
for item in data:
    d[item[0]].append((item[1:5]))

# Extract the tuples from the dictionary values using a list 
#comprehension
 values_list = [np.array(v) for v in d.values()]
#print(values_list)
# Convert the list of arrays to a 3D numpy array
my_array = np.array(values_list)
print(my_array)

但这给了我一个3个数组的列表,我只想要一个3d数组,我还使用了np.stack,但由于每个数组的长度不同,它给了我这个错误:

ValueError: all input arrays must have the 
same shape

我真的很沮丧,如果有人知道任何方法,请与我分享。

o8x7eapl

o8x7eapl1#

循环遍历每个值,并重新构造列表:

data = [(1, 65, -18, -1, -1 ),
   (1, -18,-1, -1),
   (2, 65, -19, -1, -1),
   (2, 65, -18, -1, -1),
   (3, 62, -18, -1, -1)]

[[[[val] for val in row[1:]] for row in data]]

输出:

[[[[65], [-18], [-1], [-1]],
[[-18], [-1], [-1]],
[[65], [-19], [-1], [-1]],
[[65], [-18], [-1], [-1]],
[[62], [-18], [-1], [-1]]]]
qrjkbowd

qrjkbowd2#

我认为一个简单的方法来做它并存储在一个numpy数组中是这样的

import numpy as np

data = [(1, 65, -18, -1, -1 ),
        (1, 65, -18,-1, -1),
        (2, 65, -19, -1, -1),
        (2, 65, -18, -1, -1),
        (3, 62, -18, -1, -1)]

numpy_data = np.array(data)[:,1:].reshape((5,4,1))
numpy_data

其输出

array([[[ 65],
        [-18],
        [ -1],
        [ -1]],

       [[ 65],
        [-18],
        [ -1],
        [ -1]],

       [[ 65],
        [-19],
        [ -1],
        [ -1]],

       [[ 65],
        [-18],
        [ -1],
        [ -1]],

       [[ 62],
        [-18],
        [ -1],
        [ -1]]])

从中你可以随心所欲地操纵

cwxwcias

cwxwcias3#

应用np.unique + np.split的组合,根据初始arr的第1列中包含的“id”获得数组组:

arr = np.asarray(data)
groups = np.split(arr[:, 1:], np.unique(arr[:, 0], return_index=True)[1])[1:]
groups = [a.reshape(-1, a.shape[1], 1) for a in groups]
print(groups)
[array([[[ 65],
        [-18],
        [ -1],
        [ -1]],

       [[-18],
        [ -1],
        [ -1],
        [ -1]]]),
 array([[[ 65],
        [-19],
        [ -1],
        [ -1]],

       [[ 65],
        [-18],
        [ -1],
        [ -1]]]),
 array([[[ 62],
        [-18],
        [ -1],
        [ -1]]])]

相关问题