Home > OS >  Combine lists from several columns into one nested list pandas
Combine lists from several columns into one nested list pandas

Time:10-26

Here is my dataframe:

| col1     | col2      | col3     |
----------------------------------
[1,2,3,4] | [1,2,3,4] | [1,2,3,4]

I also have this function:

def joiner(col1,col2,col3):
    snip = []
    snip.append(col1)
    snip.append(col2)
    snip.append(col3)
    return snip

I want to call this on each of the columns and assign it to a new column.

My end goal would be something like this:

| col1     | col2      | col3     | col4
------------------------------------------------------------------
[1,2,3,4] | [1,2,3,4] | [1,2,3,4] | [[1,2,3,4],[1,2,3,4],[1,2,3,4]]

CodePudding user response:

Just .apply list on axis=1, it'll create lists for each rows

>>> df['col4'] = df.apply(list, axis=1)

OUTPUT:

           col1          col2          col3  col4
0  [1, 2, 3, 4]  [1, 2, 3, 4]  [1, 2, 3, 4]  [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

CodePudding user response:

You can just do

df['col'] = df.values.tolist()
  • Related