繁体   English   中英

如何从列表中更改或创建新的 ndarray

[英]How to change or create new ndarray from list

我有ndarray类型的值 X, shape: (40000, 2)

X 的第二列包含 50 个数字的列表

例子:

[17, [1, 2, 3, ...]], 
[39, [44, 45, 45, ...]], ...

我想将其转换为shape (40000, 51)ndarray

第一列将是相同的

列表的每个元素都将在它自己的列中。

对于我的例子:

[17, 1, 2, 3, ....],
[39, 44, 45, 45, ...]

我该怎么做?

np.hstack((arr[:,0].reshape(-1,1), np.array(arr[:,1].tolist())))

例子:

>>> arr
array([[75, list([90, 39, 63])],
       [20, list([82, 92, 22])],
       [80, list([12, 6, 89])],
       [79, list([11, 96, 74])],
       [96, list([26, 37, 65])]], dtype=object)
>>> np.hstack((arr[:,0].reshape(-1,1),np.array(arr[:,1].tolist()))).astype(int)
array([[75, 90, 39, 63],
       [20, 82, 92, 22],
       [80, 12,  6, 89],
       [79, 11, 96, 74],
       [96, 26, 37, 65]])

您可以对 ndarray 的每一行执行此操作,这是一个示例:

# X = [39, [44, 45, 45, ...]]
newX = numpy.ndarray(shape=(1,51))

new[0] = X[0] # adding the first element

# now the rest of elements
i = 0
for e in X[1] : 
    newX[i] = e
    i = i + 1

您可以将此过程作为 function 并以这种方式应用:

newArray = numpy.ndarray(shape=(40000,51))

i = 0
for x in oldArray :
    Process(newArray[i],x)
    i=i+1

我将源数组(第 1 列中的列表较短)定义为:

X = np.array([[17, [1, 2, 3, 4]], [39, [44, 45, 45, 46]]])

要完成您的任务,请定义以下 function:

def myExplode(row):
    tbl = [row[0]]
    tbl.extend(row[1])
    return tbl

然后将其应用于每一行:

np.apply_along_axis(myExplode, axis=1, arr=X)

结果是:

array([[17,  1,  2,  3,  4],
       [39, 44, 45, 45, 46]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM