2

There is a X DataFrame.

X=pd.DataFrame({'x':[1,2,3,4,5],'y':[6,7,8,9,10],'z':[11,12,13,14,15]})

I want to make a,b,c like this.

a=array([1,2,3,4,5])
b=array([6,7,8,9,10])
c=array([11,12,13,14,15])

However When i run the code below,

a,b,c=np.array(X)

I got an error

ValueError: too many values to unpack (expected 3)

I should change this part np.array(X) not a,b,c because of package code i am using. But i don't know how to fix it..

1 Answer 1

1

Use pandas.DataFrame.to_numpy() to convert to numpy.array, then transpose it using numpy.ndarray.T, and then use numpy.split

>>> a,b,c = np.split(X.to_numpy().T, [1,2])

>>> a
array([[1, 2, 3, 4, 5]], dtype=int64)

>>> b
array([[ 6,  7,  8,  9, 10]], dtype=int64)

>>> c
array([[11, 12, 13, 14, 15]], dtype=int64)

If there are guaranteed to be 3 columns only, you can just assign the transposed array

>>> a,b,c = X.to_numpy().T

If you want list, then:

>>> a,b,c = X.to_numpy().T.tolist()
Sign up to request clarification or add additional context in comments.

2 Comments

Why split? a, b, c = X.to_numpy().T is enough.
True, just made sure the code doesn't break if more columns are added. But I should mention it probably. Thanks.

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.