Fetching elements from multiple columns of lists in a dataframe

user861938 :

I have a dataframe like this:

     A            B             C
  [1,2,3]    ['a','b','c']    ['aa', 'bb', 'cc']
  [4,5,6]    ['d','e','f']    ['dd', 'ee', 'ff']
  [7,8,9]    ['g','h','i']    ['gg', 'hh', 'ii']

I would like to combine the values from these columns as follows:

[[[1,'a', 'aa'], [2,'b','bb'], [3, 'c', 'cc']], [[4,'d','dd'], [5,'e', 'ee'], [6,'f','ff']], [[7,'g','gg'], [8,'h','hh'], [9,'i','ii']]]

My idea was to change each column to list like this (which will give a list of list) :

first = df['A'].values.tolist() # similarly for other columns

And then zip all lists and iterate through them and fetch corresponding values from each list and create a new list as per the output format. But, I am sure there are better solutions than mine. Can anyone help me with this?

YOBEN_S :

IIUC explode with groupby

pd.concat([df[[x]].explode(x) for x in df.columns],axis=1)\
     .apply(lambda x : x.tolist(),axis=1).groupby(level=0).agg(list).tolist()
Out[366]: 
[[[1, 'a', 'aa'], [2, 'b', 'bb'], [3, 'c', 'cc']],
 [[4, 'd', 'dd'], [5, 'e', 'ee'], [6, 'f', 'ff']],
 [[7, 'g', 'gg'], [8, 'h', 'hh'], [9, 'i', 'ii']]]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=291656&siteId=1