4

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

Kevin
  • 587
  • 1
  • 7
  • 17

2 Answers2

7

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)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 1
    You win for 15 sec, nice solution :-) – BENY Nov 16 '17 at 23:01
  • Sadly, this doesn't work with Pandas 1.x: TypeError: can only concatenate list (not "str") to list Or TypeError: Cannot broadcast np.ndarray with operand of type if you give [['t']]. – user582175 Feb 23 '21 at 13:37
1

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

df.column3 = df.column3.apply(lambda x: x+['t'])
andrew_reece
  • 20,390
  • 3
  • 33
  • 58