Dylan Ong
Dylan Ong

Reputation: 866

Converting npArrays to integers

I have an npArray of npArrays. When we print the npArray, we get

[[1] [2] [3]]

I want to change this array into an npArray with just integers in the form of

[1 2 3]

Thank you. The code is below. I already attempted it in there

a = np.array([np.array([1]),np.array([2]),np.array([3])])
print(type(a[0]))
for i in range(0,2):
    a[i] = a[i][0]

print(a)

Upvotes: 1

Views: 112

Answers (2)

CypherX
CypherX

Reputation: 7353

Solution:

a.flatten() or a.ravel() or a.reshape(1,-1) or a.T

You can use any of the following four options:

  • a.flatten() EDIT: as @PhilipPurwoko suggested in his solution.
  • a.ravel() EDIT: as @MarkMeyer also suggested in the comments section.
  • a.reshape(1,-1): reshaping to 1-row array
  • a.T: transposing will also give you your desired result here as you have a column array and you want it as a row array.

Example

import numpy as np

a = np.arange(5).reshape(-1, 1)
print(a)

## Output
# [[0]
#  [1]
#  [2]
#  [3]
#  [4]]

a.flatten() 
# array([0, 1, 2, 3, 4])

a.ravel()
# array([0, 1, 2, 3, 4])

a.reshape(1,-1)
# array([0, 1, 2, 3, 4])

a.T
# array([0, 1, 2, 3, 4])

Upvotes: 1

Philip Purwoko
Philip Purwoko

Reputation: 447

You can use flatten method

import numpy as np

a = np.array([np.array([1]),np.array([2]),np.array([3])])
print(type(a[0]))

print('Original')
print(a)

a = a.flatten()
print('Converted')
print(a)

Output :

<class 'numpy.ndarray'>
Original
[[1]
 [2]
 [3]]
Converted
[1 2 3]

Upvotes: 2

Related Questions