hydra123
hydra123

Reputation: 347

extracting a column as a vector from a matrix in python

I have a csv file , which I am converting it to a matrix using the following command:

reader = csv.reader(open("spambase_X.csv", "r"), delimiter=",")
x = list(reader)
result = numpy.array(x)
print(result.shape)   #outputs (57,4601)

Now I want to extract the first column of the matrix result , which I am doing by the following:

col1=(result[:, 1])

**print(col1.shape)        #outputs (57,)**

Why isnt it printing as (57,1). How can I do that?

TIA

Upvotes: 1

Views: 6952

Answers (3)

Arshdeep Singh
Arshdeep Singh

Reputation: 527

yes it will return the array of shape (57,). If you want to be as (57,1) , you can do it so by reshape().

col1=(result[:, 1]).reshape(-1,1)

Upvotes: 2

Francesco Montesano
Francesco Montesano

Reputation: 8658

col1 = result[:, 1] is 1D array, thus you see that the shape it (57, ).

You can convert it to a 2D array with a single column doing:

col1[:, np.newaxis]   # shape: (57, 1)

If you want a 2D array with a single row you can do:

col1[np.newaxis, :]   # shape: (1, 57)

Upvotes: 0

BENY
BENY

Reputation: 323226

You can add []

result[:,[1]].shape
Out[284]: (2, 1)

Data input

result
Out[285]: 
array([[1, 2, 3],
       [1, 2, 3]])

More Information

result[:,[1]]
Out[286]: 
array([[2],
       [2]])
result[:,1]
Out[287]: array([2, 2])

Upvotes: 1

Related Questions