繁体   English   中英

连接 Python 中坐标的 arrays

[英]Concatenate arrays of coordinates in Python

我正在从多个 d 维立方体构建坐标数组。 我想从一个空数组和 append 我在每个 for 循环中生成的坐标开始。 但是,np.concatenate(和 vstack)需要一个现有的匹配维度数组。 我也想保持维度而不是得到一个平面数组。

这是我想做的想法:

#sample from d-dimensional cube
def make_cubes(d, npoints, ncubes):
    cubes = []
    for i in range(ncubes):
        c = np.random.rand(npoints, d)     #sample from cube in d dimensions
        c += np.random.uniform(-5,5)   #random translation
        cubes = np.concatenate((cubes, c))
    return cubes

为了使它真正起作用,我必须将多维数据集定义为

cubes = [[]]
for d in range(d):
    cubes[0].append(np.nan)

正如 hpaulj 所说,您可以使用 append 而不是连接。 最后,您可以将阵列重塑为所需的形状。

#sample from d-dimensional cube
def make_cubes(d, npoints, ncubes):
    cubes = []
    for i in range(ncubes):
        c = np.random.rand(npoints, d)     #sample from cube in d dimensions
        c += np.random.uniform(-5,5)   #random translation
        cubes.append(c)
       
    cubes = np.reshape(cubes, (npoints*ncubes,d) )
    return cubes

例如

print( make_cubes(3,4,2) )

给我

[[-0.20605781  0.17759941 -0.54688093]
 [ 0.15476342 -0.47873276 -0.66528647]
 [ 0.05216092 -0.7118765  -0.2794354 ]
 [-0.648958   -0.49131152 -0.24827643]
 [ 3.80803203  3.41893782  3.66186498]
 [ 4.37535951  3.79385615  3.52051711]
 [ 3.98299149  4.17239746  4.09716118]
 [ 3.89030706  4.26959177  4.38166707]]

暂无
暂无

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

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