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

Time:12-21

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?

CodePudding user response:

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]
  • Related