gpt4 book ai didi

python - 访问 numpy ndarray 中的单个列

转载 作者:行者123 更新时间:2023-12-04 01:20:07 26 4
gpt4 key购买 nike

我有一个形状为 (m, 1,100,4) 的 nd-numpy 数组我想访问内部数组的各个列(形状: (1,100,4) )。
MWE:
例如,假设我有这个:

import numpy as np
X = np.random.randn(2, 1, 5, 4)

X
array([[[[-0.40867508, 0.09331783, 1.26134307, -1.18900601],
[-0.79177772, 0.96738931, -0.33332772, 0.53130287],
[ 3.67290383, 0.30954936, 0.63221306, -0.64003826],
[-1.20878773, 1.21499506, 1.84995811, 0.15663168],
[-0.60648072, -0.30464852, -0.44044224, -4.46482868]]],


[[[-1.90531392, -0.47108517, 1.21177166, 0.09561669],
[ 3.21803694, 0.30611821, 1.71334417, 0.73383279],
[-1.12869017, -0.1497266 , -0.54913676, 0.36704922],
[ 0.5652546 , -0.75012341, -0.72496611, 1.12428097],
[-1.19727408, -0.13813127, 2.63948821, -0.37661527]]]])
嵌套数组的形状 (1,5,4) .然后访问每个嵌套数组的第一列返回整个数组:
X[ :, 0]
array([[[-0.40867508, 0.09331783, 1.26134307, -1.18900601],
[-0.79177772, 0.96738931, -0.33332772, 0.53130287],
[ 3.67290383, 0.30954936, 0.63221306, -0.64003826],
[-1.20878773, 1.21499506, 1.84995811, 0.15663168],
[-0.60648072, -0.30464852, -0.44044224, -4.46482868]],

[[-1.90531392, -0.47108517, 1.21177166, 0.09561669],
[ 3.21803694, 0.30611821, 1.71334417, 0.73383279],
[-1.12869017, -0.1497266 , -0.54913676, 0.36704922],
[ 0.5652546 , -0.75012341, -0.72496611, 1.12428097],
[-1.19727408, -0.13813127, 2.63948821, -0.37661527]]])
我的目的是得到一个元组,这样:
s,t,u,v = X[first_columns], X[second_columns], X[third_columns], X[fouth_columns]
使得:
s =[-0.40867508, -0.79177772, 3.67290383, -1.20878773, -0.60648072,
-1.90531392, 3.21803694, -1.12869017, 0.5652546, -1.19727408]

最佳答案

你要找的是

X[:,0,:,0].ravel()
请注意,这种形状的 X ,我们不能直接以数组的形式获取所需的元素,而是以二维矩阵的形式获取。因此我们需要 reshape以数组形式。
另一个对应于:
t = X[:,0,:,1].ravel()
u = X[:,0,:,2].ravel()
v = X[:,0,:,3].ravel()

关于python - 访问 numpy ndarray 中的单个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62772470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com