-1

I have a dataframe in pandas, with a column which is a vector:

df = pd.DataFrame({'ID':[1,2], 'Averages':[[1,2,3],[4,5,6]]})

df

and I wish to split and divide it into elements which would look like this:

df2 = pd.DataFrame({'ID':[1,2], 'A':[1,4], 'B':[2,5], 'C':[3,6]})

enter image description here

I have tried df['Averages'].astype(str).str.split(' ') but with no luck. any help would be appreciated.

shahar_m
  • 3,461
  • 5
  • 41
  • 61

2 Answers2

2
pd.concat([df['ID'], df['Averages'].apply(pd.Series)], axis = 1).rename(columns = {0: 'A', 1: 'B', 2: 'C'}) 
Brian
  • 1,572
  • 9
  • 18
  • This doesn't fully solve the problem, as it returns a dataframe that does not include the 'ID' column. – exp1orer Oct 04 '18 at 15:45
  • @exp1orer Here: pd.concat([df['ID'], df['Averages'].apply(pd.Series)], axis = 1).rename(columns = {0: 'A', 1: 'B', 2: 'C'}) The essence of the problem was figuring out how to turn list-based data into multiple columns and my code solves that. You should know how to add a column in pandas and rename them. Not every answer on stackexchange should just be copy/paste. – Brian Oct 04 '18 at 16:04
  • 1
    Thanks, I'd recommend you edit your answer to include that! The OP provided a desired output, so your answer will be stronger if it produces that desired output. (Note that I'm not the OP, I came across your answer as an editor because it was recommended for deletion.) – exp1orer Oct 04 '18 at 16:27
  • 1
    @ exp1orer, thanks, updated – Brian Oct 04 '18 at 16:40
1

This will work:

df[['A','B','C']] = pd.DataFrame(df.averages.values.tolist(), index= df.index)
Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51