Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Data Science by (18.4k points)

In my Python script, I load a 1D vector from a .dat file. I want to use that vector as the first column in a matrix, where the second column is filled with 1s. This is how I did it:

I am working on vectors using python script, what I am trying to do is. I am taking a vector as my first column in my matrix, my second column consists of 1s value. This is how it looks:

x = np.loadtxt( 'x.dat' )

m = x.shape[0]

X = np.concatenate((x.reshape((m,1)), np.ones((m,1))), axis=1)

Is there any other way to achieve it?

1 Answer

0 votes
by (36.8k points)

The code you have used is completely perfect to me but if you are concerned about the performance of code then you can use this:

X = np.ones((m, 2))

X[:,0] = x


X = np.empty((m, 2))

X[:,0] = x

X[:,1] = 1

Even when you add one more column it doesn't affect your performance this might be a surprise to you. You can change your data format to instead of np.loadtxt. This is must faster.

Improve your knowledge in data science from scratch using Data Science tutorial 

Related questions

Browse Categories