Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

python - 在python中将特定值添加到3-d数组(adding a certain value to 3-d array in python)

i have a 3-d array and i want to create a new array that each second elements of 3-d array must be increased by 1 until the second element reach to a certain value.

(我有一个3-d数组,我想创建一个新数组,必须将3-d数组的每个第二元素加1,直到第二个元素达到某个值。)

for example i have a 3-d array like below as an input and need to obtain my expected output :

(例如,我有一个像下面这样的3-d数组作为输入,需要获得我的预期输出:)

#input = [[[1,1],[2,2],[3,3],[4,4]],[[1,1],[2,2],[3,3],[4,4]]]


#This is my expected output:

[[[1,1],[2,2],[3,3],[4,4]],[[1,1],[2,2],[3,3],[4,4]],
 [[1,2],[2,3],[3,4],[4,5]],[[1,2],[2,3],[3,4],[4,5]],
 [[1,3],[2,4],[3,5],[4,6]],[[1,3],[2,4],[3,5],[4,6]],
 [[1,4],[2,5],[3,6],[4,7]],[[1,4],[2,5],[3,6],[4,7]],
 [[1,5],[2,6],[3,7],[4,8]],[[1,5],[2,6],[3,7],[4,8]]]
  ask by user11794094 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using the numpy module, you could do

(使用numpy模块,您可以执行)

import numpy as np

# initial nested list to numpy nd array
arr = np.array([[[1,1],[2,2],[3,3],[4,4]],
                [[1,1],[2,2],[3,3],[4,4]]])

# expand n times along axis 0 ("x")
n = 3
arr = np.repeat(arr, n, axis=0)

# what you want to add
add = np.repeat(np.arange(n), arr.shape[1]*2)

# bring to adequate shape
add.shape = arr.shape[:2]

# perform addition
arr[:,:,1] += add

arr would now be

(arr现在会是)

array([[[1, 1],
        [2, 2],
        [3, 3],
        [4, 4]],

       [[1, 1],
        [2, 2],
        [3, 3],
        [4, 4]],

       [[1, 2],
        [2, 3],
        [3, 4],
        [4, 5]],

       [[1, 2],
        [2, 3],
        [3, 4],
        [4, 5]],

       [[1, 3],
        [2, 4],
        [3, 5],
        [4, 6]],

       [[1, 3],
        [2, 4],
        [3, 5],
        [4, 6]]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...