0

I want to simply assign 1 into all list of a ndarray.

before,

[5.2 4.1]
[6.9 3.1]
[5.9 3.2]
[5.6 2.8]
[6.7 3.3]......................

what i need,

[1 5.2 4.1]
[1 6.9 3.1]
[1 5.9 3.2]
[1 5.6 2.8]
[1 6.7 3.3]

i am trying to iterate and insert, then try to assign the returned value. but i have a problem with the shape. found the above error.

for i in range(len(X_train)):
  X_train[i] = np.insert(X_train[i], 0,1)

then i tried to reshape before loop:

X_train = X_train.reshape(len(X_train), 3)

i found this error: cannot reshape array of size 210 into shape (105,3)

but the actual shape:

>>X_train.shape

output: (105, 2)

I am looking for any solution and also the reason. thanks in advance.

0

3 Answers 3

1

From the insert docs:

>>> a = np.array([[1, 1], [2, 2], [3, 3]])
>>> a
array([[1, 1],
       [2, 2],
       [3, 3]])
>>> np.insert(a, 1, 5, axis=1)
array([[1, 5, 1],
       [2, 5, 2],
       [3, 5, 3]])

So taking your case - act on the whole array, and specify the axis:

In [184]: arr = np.random.randint(0,9,(3,2))
In [185]: arr
Out[185]: 
array([[7, 5],
       [2, 0],
       [2, 4]])
In [186]: arr1 = np.insert(arr,0,1,axis=1)   
In [187]: arr1
Out[187]: 
array([[1, 7, 5],
       [1, 2, 0],
       [1, 2, 4]])

Many of the numpy functions take an axis (or axes) parameter. Use it.

Sign up to request clarification or add additional context in comments.

Comments

1

One Liner:

import numpy as np
X_train = np.hstack((X_train, np.ones((X_train.shape[0], 1), dtype=X_train.dtype)))

Comments

0

Just create an array of ones and fill all but the first column with your starting array.

import numpy as np
arr = np.array(
[[5.2, 4.1],
[6.9, 3.1],
[5.9, 3.2],
[5.6, 2.8],
[6.7, 3.3]])
sh =arr.shape

new_arr = np.ones((sh[0],sh[1]+1))
new_arr[:,1:] = arr

print(new_arr)

Output :

[[1.  5.2 4.1]
 [1.  6.9 3.1]
 [1.  5.9 3.2]
 [1.  5.6 2.8]
 [1.  6.7 3.3]]

1 Comment

its a dataset actually, so i have to iterate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.