13

suppose I have a DataFrame similar to this:

d = {'col1': [0, 2, 4], 'col2': [1, 3, 5], 'col3': [2, 4, 8]}
df = pd.DataFrame(d)

   col1  col2  col3
0     0     1     2
1     2     3     4
2     4     5     8

How can I select col1 and col2 and turn them into this array?

array([[0, 1],
       [2, 3],
       [4, 5]])

2 Answers 2

27

You can access the underlying numpy array via the to_numpy method:

df[['col1', 'col2']].to_numpy()
Out: 
array([[0, 1],
       [2, 3],
       [4, 5]])

.values attribute will do the same if you are on an earlier version (before v0.24).

Sign up to request clarification or add additional context in comments.

Comments

1

You can also achieve the same output with the below code.

import numpy as np
np.array(df[['col1','col2']])
Out[60]: 
array([[0, 1],
       [2, 3],
       [4, 5]])

Comments

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.