user2268997
user2268997

Reputation: 1391

Creating a Pandas DataFrame with a single vector column from a 2-d numpy array

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?

Upvotes: 1

Views: 1036

Answers (1)

user17242583
user17242583

Reputation:

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]

Upvotes: 4

Related Questions