How to turn a Pandas column into array and transpose it?
Asked Answered
S

3

12

I have a Pandas dataframe called 'training_set' that resembles the screenshot below:

enter image description here

I try to turn the 'label' column into array and transpose it. I tried doing Y_train=np.asarray(training_set['label']) but what I got is a horizontal array that resembles the screenshot below, which is not what I want.

enter image description here

I want the array to display vertically just like the screenshot below (The screenshot has 2 variables per row. My desired output should only contain 1 variable, the 'label', per row.)

enter image description here

Any suggestion or help would be greatly appreciated!

Sapro answered 28/3, 2018 at 23:9 Comment(0)
M
25

pandas >= 0.24

Use DataFrame.to_numpy(), the new Right Way to extract a numpy array:

training_set[['label']].to_numpy()

pandas < 0.24

Slice out your column as a single columned DataFrame (using [[...]]), not as a Series:

Y_train = np.asarray(training_set[['label']])

Or,

Y_train = training_set[['label']].values
Monarchal answered 28/3, 2018 at 23:12 Comment(0)
S
3

Another way would be to reshape your array to shape (-1,1), which means "infer number of rows, force to 1 column":

Y_train = np.array(training_set['label']).reshape(-1,1)
Spelunker answered 28/3, 2018 at 23:21 Comment(0)
S
3

One way:

Y_train = training_set['label'].values[:, None]
Sestertium answered 28/3, 2018 at 23:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.