0

This is the current dataframe I have: It is Nx1 with each cell containing a numpy array.

print (df)
          age  
0   [35, 34, 55, 56]
1   [25, 34, 35, 66] 
2   [45, 35, 53, 16]
.
.
.
N   [45, 35, 53, 16]

I would like somehow to ravel each value of each cell to a new column.

# do conversion
print (df)

   age1  age2  age3  age4
0   35    34    55    56  
1   25    34    35    66  
2   45    35    53    16  
.
.
.
N   45    35    53    16  
azal
  • 1,210
  • 6
  • 23
  • 43
  • Hmmm, I see you choose `.apply(pd.Series)` solution. What is reason? If check [this](https://stackoverflow.com/a/35491399/2901002) is is really slow. – jezrael Dec 12 '19 at 15:17

4 Answers4

3

You can reconstruct the dataframe from the lists, and customize the column names with:

df = pd.DataFrame(df.age.values.tolist())
df.columns += 1
df = df.add_prefix('age')

print(df)

   age1  age2  age3  age4
0    35    34    55    56
1    25    34    35    66
...
yatu
  • 86,083
  • 12
  • 84
  • 139
0

Here is another alternative:

import pandas as pd
df = pd.DataFrame({'age':[[35,34,55,54],[1,2,3,4],[5,6,7,8],[9,10,11,12]]})
df['age_aux'] = df['age'].astype(str).str.split(',')
for i in range(4):
    df['age_'+str(i)] = df['age_aux'].str.get(i).map(lambda x: x.lstrip('[').rstrip(']'))
df = df.drop(columns=['age','age_aux'])
print(df)

Output:

  age_0 age_1 age_2 age_3
0    35    34    55    54
1     1     2     3     4
2     5     6     7     8
3     9    10    11    12
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
0

You can create DataFrame by constructor for improve performance and change columns names by rename with f-strings:

df1 = (pd.DataFrame(df.age.values.tolist(), index=df.index)
         .rename(columns = lambda x: f'age{x+1}'))
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
-1

Another variation is to apply pd.Series to the column and massage the column names:

df= pd.DataFrame( { "age": [[1,2,3,4],[2,3,4,5]] })

df = df["age"].apply(pd.Series)
df.columns = ["age1","age2","age3","age4"]
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28