简体   繁体   中英

operation on numpy array in Python

I have one array and i want to convert it into certain shape which I do not know how to do.

I tried, but it does not give me proper result.

Here is the array-: this is a numpy array

a=[[ [1,2,13],
     [12,2,32],
     [61,2,6],
     [1,23,3],
     [1,21,3],
     [91,2,38] ]]

expected outputs-:

1. [[ [1,2],
      [12,2],
      [61,2],
      [1,23],
      [1,21], 
      [91,2] ]]

2.  [ [1,2],
       [12,2],
       [61,2],
       [1,23],
       [1,21],
       [91,2] ]

So the question can be boiled down to

"Given a 3D numpy array with the shape (1, 6, 3) how can we make a copy but a shape of (1, 6, 2) by removing the last indexed value from the innermost nested array?"

Array Indexing

The below example achieves this by slicing the original array ( a ) to return the desired structure.

import numpy as np

a = np.array([[[1,2,13],[12,2,32],[61,2,6],[1,23,3],[1,21,3],[91,2,38]]])
o = a[:,:,:2]

List Comprehension

The below makes use of a list comprehension applied to filter a down in the manner described above.

import numpy as np

a = np.array([[[1,2,13],[12,2,32],[61,2,6],[1,23,3],[1,21,3],[91,2,38]]])
o = np.array([[j[:2] for i in a for j in i]])

In each of the above examples o will refer to the following array (the first output you are asking for).

array([[[ 1,  2],
        [12,  2],
        [61,  2],
        [ 1, 23],
        [ 1, 21],
        [91,  2]]])

Given o as defined by one of the above examples, your second sought output is accessible via o[0] .

This will do

import numpy as np
a=[[ [1,2,13],
     [12,2,32],
     [61,2,6],
     [1,23,3],
     [1,21,3],
     [91,2,38] ]]
outputs=list()
for i in a[0]:
  outputs.append([i[0],i[1]])
print(np.array([outputs]))
""" OUTPUTS
[[[ 1  2]
  [12  2]
  [61  2]
  [ 1 23]
  [ 1 21]
  [91  2]]]
"""

Instead of deriving output2 = output1[0] you could use squeeze method. It removes all the single - dimensional entries from your array

output1 = a[:,:,:2]
output2 = output1.squeeze() 

This is a vizualization of a process for a better understanding:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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