Pandas: how to use apply with a series of lists

Viewed 751

I have a Pandas series of lists:

| id | values         |
| -- | -------------- |
| 0  | ['a', 'b']     |
| 1  | ['c']          |
| 2  | ['b', 'c']     |

I want to apply a function to each of the lists.

Let's use a really simple function that just adds 'd' to each list, and apply it to the series:

def append_d(x):
    print(x)
    return x + ['d']
my_series.apply(append_d)

This results in an error:

Cannot broadcast np.ndarray with operand of type <class 'list'>

I have tried the following:

my_series.apply(lambda x: x + ['d']) # same error as above
my_series.transform(append_d) # ValueError: Transform function failed
my_series.transform(lambda x: x + ['d']) # ValueError: Transform function failed

How do I use apply/transform with a series of lists?

2 Answers

Just use apply() method:-

df['values'].apply(lambda x:x.append('d'))

Now if you print your df you will get your desired output:-

    values
0   [a, b, d]
1   [c, d]
2   [b, c, d]

Problem is need processing Series, it means column values instead DataFrame called series:

print (type(series))
<class 'pandas.core.frame.DataFrame'>

print (type(series['values']))
<class 'pandas.core.series.Series'>

series['values'].apply(lambda x: x + ['d'])

Better is called DataFrame df and then use:

df['values'].apply(lambda x: x + ['d'])
Related