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

Friday, May 13, 2022

[FIXED] how to append a 1d numpy array to a 2d numpy array python

 May 13, 2022     append, numpy, python     No comments   

Issue

I would like to append an array [3, 3, 3] to an array [[1, 1, 1], [2, 2, 2]], so that it becomes [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

Here is my code:

import numpy as np
arr1 = np.array([[1, 1, 1], 
                 [2, 2, 2]])

arr2 = np.append(arr1, [3, 3, 3])

print (arr2)

instead of printing [[1, 1, 1], [2, 2, 2], [3, 3, 3]],

it prints [1, 1, 1, 2, 2, 2, 3, 3, 3].

I am quite new to numpy and I do not understand why the 2d array suddenly becomes 1d.


Solution

You can use the useful numpy's standard method of vstack.

Here is my code.

Initialize 2-dimensional numpy array

initial_array = np.array([
    [1, 1, 1], 
    [2, 2, 2]
])

define the array to append to initiali array

new_array = np.array([3, 3, 3])

append the new array to initial array as row

result = np.vstack((initial_array, new_array))

this is the result

print(result)
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

You can read more details at here.

Hope this answer to be helpful for you. Thanks.



Answered By - Dragan Kojić
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • 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