Search code examples
pythonpandas

Functional equivalent in pandas to assigning one or more elements in a series


I am wondering if there is a functional but efficient equivalent to the following mutative code:

import pandas as pd

s = pd.Series(...)
s[k] = v   # I don't want to mutate s

so that the operation returns a new series s2 with the mutation. I can use copy() and then mutate; for example:

import pandas as pd
import numpy as np

t = np.arange(100)
s = pd.Series(t*t,t)
s2 = s.copy()
s2[[3,4]] = [44,55]
s2

but is there a way to do it in one swoop and return a new Series without changing the existing series, like with apply or map or replace... but here I know the indices and the values I want to change.


Solution

  • There isn't a straightforward method to do this. Your copy+assign approach is actually fine (this is what I would do, and a common trick in )

    map, apply and replace consider the values, not the indices.

    The easiest that comes to my mind for a functional approach would be to craft a Series with the indices and values to replace and to combine_first:

    pd.Series([44, 55], index=[3, 4]).combine_first(s)
    

    And if you need this in a pipeline:

    s2 = (pd.Series(t*t,t)
            .pipe(pd.Series([44, 55], index=[3, 4]).combine_first)
           #.other(...)
         )
    

    Output:

    0     0
    1     1
    2     4
    3    44
    4    55
    5    25
    6    36
    7    49
    8    64
    9    81
    ...
    dtype: int64