2

I have a DataFrame that looks like:

              a   b
0  [1., 2., 3.]   1.
1  [4., 5., 6.]   2.

I want a 2d numpy array that takes the list from column a and appends values from column b, like so:

[[1., 2., 3., 1.],
 [4., 5., 6., 2.]]

I've tried unsuccessfully:

>>>np.c_[df.a, df.b]

array([[array([1., 2., 3.], dtype=float32), 1.],
      [[array([4., 5., 6.], dtype=float32), 2.]], dtype=object)

Variants of np.hstack or np.append lead to the same result.

1 Answer 1

1

You can use numpy.append with .apply(), as follows:

df.apply(lambda x:  np.append(x['a'], x['b']), axis=1).to_numpy()

Result:

array([array([1, 2, 3, 1]), 
       array([4, 5, 6, 2])], dtype=object)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it worked. For future viewers, I'll add that if you want to add more columns like this, you can try : df.apply(lambda x: np.append(x['a'], (x['b'], x['c'])), axis=1).to_numpy()

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.