Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List append in pandas cell

I have a dataframe which contains list item in a column.

Example: df:

column1, column2, column3
1         'c'       ['d']
2         'x'       []
3         'foo'     ['car']

so I want to append another item into column3

the result should be like this

column1, column2, column3
1         'c'       ['d','t']
2         'x'       ['t']
3         'foo'     ['car','t']

Currently I use the method like this

df['column3']=df['column3'].apply(lambda x: x.append('t'))

But the the column3 became

column1, column2, column3
1         'c'       none
2         'x'       none
3         'foo'     none

Wonder how to do that using apply function

like image 302
Kevin Avatar asked Oct 20 '25 22:10

Kevin


2 Answers

Just use:

df['column3'] += ['t']

Instead of apply. The problem is .append works in-place and returns None

You of course could do something silly if you really wanted to use .apply + lambda:

df.column3.apply(lambda x: x.append('t') or x)
like image 195
juanpa.arrivillaga Avatar answered Oct 23 '25 14:10

juanpa.arrivillaga


Here's how to do it with apply(). Use + instead of append().

df.column3 = df.column3.apply(lambda x: x+['t'])
like image 33
andrew_reece Avatar answered Oct 23 '25 13:10

andrew_reece



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!