PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How to append a new element into 3D numpy array in a loop?

 May 13, 2022     append, insert, multidimensional-array, numpy, python     No comments   

Issue

I wanted to try to add a new element into the 3D numpy array in loop python but it didn't work with insert or append.

import numpy as np
a = np.array([[[24,24,3],[25,28,1],[13,34,1],[3,4,5]]])
a = np.insert(a,3,0,axis = 2)
print(a)
[[[24 24  3  0]
 [25 28  1  0]
 [13 34  1  0]
 [ 3  4  5  0]]]

I don't want to insert 0 to each array but with a for loop

for i in range(4):
 .......

The result should be like this:

[[[24 24  3  0]
 [25 28  1  1]
 [13 34  1  2]
 [ 3  4  5  3]]]

Solution

You can't do this piecemeal. Think rather terms of concatenating a wwhole column or plane at once. The array has to remain 'rectangular' - no raggedness.

In [276]: a = np.array([[[24,24,3],[25,28,1],[13,34,1],[3,4,5]]])
In [277]: a.shape
Out[277]: (1, 4, 3)
In [278]: x = np.arange(4).reshape(1,4,1)
In [279]: x
Out[279]: 
array([[[0],
        [1],
        [2],
        [3]]])
In [280]: arr1 =np.concatenate((a,x), axis=2)
In [281]: arr1.shape
Out[281]: (1, 4, 4)
In [282]: arr1
Out[282]: 
array([[[24, 24,  3,  0],
        [25, 28,  1,  1],
        [13, 34,  1,  2],
        [ 3,  4,  5,  3]]])

alternatively

In [290]: arr2=np.zeros((1,4,4),int)
In [291]: arr2[:,:,:3]=a
     ...: arr2
Out[291]: 
array([[[24, 24,  3,  0],
        [25, 28,  1,  0],
        [13, 34,  1,  0],
        [ 3,  4,  5,  0]]])
In [292]: for i in range(4):
     ...:     arr2[:,i,3]=i
     ...: 
In [293]: arr2
Out[293]: 
array([[[24, 24,  3,  0],
        [25, 28,  1,  1],
        [13, 34,  1,  2],
        [ 3,  4,  5,  3]]])


Answered By - hpaulj
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing