Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine lists from several columns into one nested list pandas

Tags:

python

pandas

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]]
like image 786
Matthew D'vertola Avatar asked Oct 28 '25 03:10

Matthew D'vertola


1 Answers

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]]
like image 113
ThePyGuy Avatar answered Oct 29 '25 19:10

ThePyGuy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!