1

I would like to add a column of '1's on all my rows of first column... For example, before:

9 8 4
3 4 5
3 2 1

after:

1 9 8 4
1 3 4 5
1 3 2 1 

My code so far:

import numpy as np
import pandas as pd

training = pd.read_csv('data.csv', header = None)
training
training.shape

Output = (300, 14)

To make data into a matrix:

trainingData = training.values

Insert a column of 1's in the first column on all rows

featureVector = np.insert(featureVector, 0, 1, axis=0)

When I print the variable featureVector, I don't see the 1's...how can I do this or fix it?

1
  • Try with axis=1, since you want to change the number of columns. Commented Oct 7, 2017 at 21:10

3 Answers 3

1

This worked for me:

array = training.values
np.concatenate(([np.ones(len(array))],array.T),axis=0).T
Sign up to request clarification or add additional context in comments.

Comments

1

With numpy.insert() routine:

import numpy as np

training = np.loadtxt('data.csv', dtype=int)
training = np.insert(training, 0, 1, axis=1)
print(training)

The output:

[[1 9 8 4]
 [1 3 4 5]
 [1 3 2 1]]

3 Comments

So basically he/she had the axis wrong. Nice one! +1
just curious, why do you use np.loadtxt() over pd.read_csv? can np.loadtxt() handle large data sets?
@KatZee, just seen that simple input data and thought that the job could be done with single numpy module(without pandas). Of course, you may continue to use pandas
0

You could concatenate a 1-column matrix and training :

>>> import numpy as np
>>> training = np.array([9, 8, 4, 3, 4, 5, 3, 2, 1]).reshape(3, 3)
>>> np.concatenate((np.ones((training.shape[1], training)), a), axis=1)
array([[ 1.,  9.,  8.,  4.],
       [ 1.,  3.,  4.,  5.],
       [ 1.,  3.,  2.,  1.]])

axis=1 is used to specify that a column should be added. Otherwise:

>>> np.concatenate(([[1,1,1]], training), axis=0)
array([[1, 1, 1],
       [9, 8, 4],
       [3, 4, 5],
       [3, 2, 1]])

You could also use column_stack:

>>> np.column_stack((np.ones(training.shape[1]), training))
array([[ 1.,  9.,  8.,  4.],
       [ 1.,  3.,  4.,  5.],
       [ 1.,  3.,  2.,  1.]])

1 Comment

would I have to make a loop if I wanted to change 300 rows in the first column?

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.