1

I have a numpy 2D-array:

arr = [
  [10, 20],
  [30, 40]
]

Converting it into a pandas dataframe with pd.DataFrame(arr) gives me:

    0  1
0  10 20
1  30 40

I am looking for something like this:

          0
0  [10, 20]
1  [30, 40]

I can achieve it using

df.agg(lambda x: np.array(x), axis="columns")

or

df.agg(lambda x: [y for y in x], axis="columns")

But is there a better way to end up with the single column dataframe in the first place?

2
  • df.agg gives you a series, no? Commented Dec 20, 2021 at 22:06
  • Don't ask side-questions. Instead, if you really want to know, ask a new SO question. Questions here can actually get closed for "Needs more focus: This question includes multiple questions in one. ..." ;) Commented Dec 20, 2021 at 22:06

1 Answer 1

4

You can convert it to a list first, then a Series first, and finally a DataFrame:

df = pd.DataFrame(pd.Series(arr.tolist()))

Or, as @QuangHoang suggested:

df = pd.Series(arr.tolist()).to_frame()

Output:

>>> df
          0
0  [10, 20]
1  [30, 40]
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe pd.Series(arr).to_frame() as well.

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.