Extend lists within a pandas Series

pandas, python

Solution

Consider the series `s`

s = pd.Series([[1, 0], [2, 2], [4, 1]], list('ABC'), name='group')

s

A    [1, 0]
B    [2, 2]
C    [4, 1]
Name: group, dtype: object

You can extend each list with a similar series simply by adding them. `pandas` will use the underlying objects `__add__` method to combine the pairwise elements. In the case of a `list`, the `__add__` method concatenates the lists.

s + s

A    [1, 0, 1, 0]
B    [2, 2, 2, 2]
C    [4, 1, 4, 1]
Name: group, dtype: object

However, this would not work if the elements were `numpy.array`

s = pd.Series([[1, 0], [2, 2], [4, 1]], list('ABC'), name='group')
s = s.apply(np.array)

In this case, I'd make sure they are lists

s.apply(list) + s.apply(list)

A    [1, 0, 1, 0]
B    [2, 2, 2, 2]
C    [4, 1, 4, 1]
Name: group, dtype: object

Problem

I have a pandas series that looks like this: ``` group A [1,0,5,4,6,...] B [2,2,0,1,9,...] C [3,5,2,0,6,...] ``` I have similar series that I would like to add to the existing series by extending each of the lists. How can I do this? I tried ``` for x in series: x.extend(series[series.index[x]]) ``` but this isn't working.

Original source