-1

I've a data frame and one of its columns contains a list.

             A         B
0            5    [3, 4]
1            4    [1, 1]
2            1    [7, 7]
3            3    [0, 2]
4            5    [3, 3]
5            4    [2, 2]

The output should look like this:

             A      x    y
0            5      3    4
1            4      1    1
2            1      7    7
3            3      0    2
4            5      3    3
5            4      2    2

I have tried these options that I found here but its not working.

astroluv
  • 798
  • 1
  • 8
  • 25
  • `df[['A']].join(pd.DataFrame(df.B.values.tolist(),columns=['x','y'],index=df.index))` the same solution works for me.if not please edit the question with more details – anky Jul 21 '19 at 10:32
  • Nah it gave this error: "Shape of passed values is (1, 14316), indices imply (2, 14316)" – astroluv Jul 21 '19 at 10:37

1 Answers1

2
df = pd.DataFrame(data={"A":[0,1],
                       "B":[[3,4],[1,1]]})
df['x'] = df['B'].apply(lambda x:x[0])
df['y'] = df['B'].apply(lambda x:x[1])
df.drop(['B'],axis=1,inplace=True)
    A   x   y
0   0   3   4
1   1   1   1

Incase the list is stored as string

from ast import literal_eval
df = pd.DataFrame(data={"A":[0,1],
                       "B":['[3,4]','[1,1]']})
df['x'] = df['B'].apply(lambda x:literal_eval(x)[0])
df['y'] = df['B'].apply(lambda x:literal_eval(x)[1])
df.drop(['B'],axis=1,inplace=True)

3rd way credit goes to @anky_91

df = pd.DataFrame(data={"A":[0,1],
                       "B":['[3,4]','[1,1]']})
df["B"] = df["B"].apply(lambda x :literal_eval(x))
df[['A']].join(pd.DataFrame(df["B"].values.tolist(),columns=['x','y'],index=df.index))
df.drop(["B"],axis=1,inplace=True)

Community
  • 1
  • 1
tawab_shakeel
  • 3,701
  • 10
  • 26