0

say i have a dataframe:

              x

0     [0.5, 1.5, 2.5, 3.5, 4.5]
1     [5.5, 6.5, 7.5]
2     [8.5, 9.5, 10.5, 11.5]
3     [12.5, 13.5, 14.5, 15.5]

and i want to split the values to three separate columns(each column with two values each) as:

              a             b            c 

0      [0.5, 1.5]      [2.5, 3.5]      [4.5]
1      [5.5, 6.5]      [7.5]             0
2      [8.5, 9.5]      [10.5, 11.5]      0
3      [12.5, 13.5]    [14.5, 15.5]      0

how do i do this?

2 Answers2

2

First I think working with lists in pandas is not good idea.

But possible, use list comprehension wit custom function and DataFrame constructor:

#https://stackoverflow.com/a/312464/2901002
def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]


df1 = pd.DataFrame([list(chunks(x, 2)) for x in df['x']]).fillna(0)
print (df1)
              0             1      2
0    [0.5, 1.5]    [2.5, 3.5]  [4.5]
1    [5.5, 6.5]         [7.5]      0
2    [8.5, 9.5]  [10.5, 11.5]      0
3  [12.5, 13.5]  [14.5, 15.5]      0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

You have not mentioned if c will have anything after fourth element or just next two in case the list has more than six elements.

This is the code if you want everything after fourth element in c

df['a']=df['x'].apply(lambda x:x[:2] if len(x)>0 else 0)
df['b']=df['x'].apply(lambda x:x[2:4] if len(x)>2 else 0)
df['c']=df['x'].apply(lambda x:x[4:] if len(x)>4 else 0)
df.drop('x',axis=1,inplace=True)

Or, This is the code if you want two element in c even if the list has more after fourth element

df['a']=df['x'].apply(lambda x:x[:2] if len(x)>0 else 0)
df['b']=df['x'].apply(lambda x:x[2:4] if len(x)>2 else 0)
df['c']=df['x'].apply(lambda x:x[4:6] if len(x)>4 else 0)
df.drop('x',axis=1,inplace=True)