user10058946
user10058946

Reputation:

What does x[:,[0,1,2,2]](a kind of splicing) mean in numpy arrays in python? I was executing the following in anaconda

In Numpy using numpy.ones, I got this

import numpy as np

x=np.ones((3,3))
print(x)
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

x[:,[1,1,1,1]]
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])

Upvotes: 0

Views: 678

Answers (1)

HasnainMamdani
HasnainMamdani

Reputation: 134

x[:, [0,1,2,2]] means you are taking (all the rows of) columns 0,1,2 and 2 and combining them. Since you have all ones in your data, it is hard to visualize but the following example will help:

x = np.array([[1,2,3],[4,5,6],[7,8,9]])
x
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])


x[:, [0]]
array([[1],
       [4],
       [7]])

x[:, [1]]
array([[2],
       [5],
       [8]])

x[:, [2]]
array([[3],
       [6],
       [9]])


x[:, [0, 2, 1, 1]]
out: array([[1, 3, 2, 2],
            [4, 6, 5, 5],
            [7, 9, 8, 8]])

Upvotes: 2

Related Questions