Home > Net >  How can I make my dataframe into a numpy array by column rather than by row?
How can I make my dataframe into a numpy array by column rather than by row?

Time:12-14

Consider that I have this example dataframe:

d = {'Gender': [1,1,0,1,0], 'Employed': [1,0,0,1,1]}

I would like this to be an array of this form:

[[1 1 0 1 0][1 0 0 1 1]]

When I run

d[['Gender', 'Employed']].to_numpy()

I get an array of the form [[1 1][1 0][0 0][1 1][0 1]].

CodePudding user response:

You can transpose the DataFrame, get the underlying numpy array with values method and convert to a list with tolist method:

out = pd.DataFrame(d).T.values.tolist()

Output:

[[1, 1, 0, 1, 0],
 [1, 0, 0, 1, 1]]

CodePudding user response:

This can get your expected output

import pandas as pd
df = pd.DataFrame({'Gender': [1,1,0,1,0], 'Employed': [1,0,0,1,1]})
print([df[column].to_list() for column in df])

Output:

[[1, 1, 0, 1, 0], [1, 0, 0, 1, 1]]

Let me know if you expect more from here.

CodePudding user response:

Just transpose it.

d[['Gender', 'Employed']].values.T
  • Related