pandas.Series.apply return None but does change the dataframe correctly

Question:

Here is the problem described with an example:

My pandas.Series looks like this:

>>> epitope_charge_detail
PyDev console: starting.
Index
1       {56PD_DQ, 185T_DQ, 45EV_DQ, 167H_DQ, rq26Y, 55...
2       {66DR_DQ, 3P_DQ, 66D_DQ, 86G_DR, rq57S, 57S_DR...
3       {56PS_DQ, 185I_DQ, rqp57A, rq57S, 13GM_DQ, 56P...
5                                                      {}
6                                                      {}
                              ...                        
2141                                                   {}
2142                                                   {}
2143                                                   {}
2144                                                   {}
2145                                                   {}
Name: EpMismatches, Length: 2144, dtype: object

I use the apply function:

epitope_charge_detail.apply(lambda set_: set_.add(2))
Index
1       None
2       None
3       None
5       None
6       None
        ... 
2141    None
2142    None
2143    None
2144    None
2145    None
Name: EpMismatches, Length: 2144, dtype: object

It returns a Series full of None, but, my initial pandas.Series was successfully modified:

epitope_charge_detail
Index
1       {56PD_DQ, 185T_DQ, 2, 45EV_DQ, 167H_DQ, rq26Y,...
2       {66DR_DQ, 2, 3P_DQ, 66D_DQ, 86G_DR, rq57S, 57S...
3       {2, 56PS_DQ, 185I_DQ, rqp57A, rq57S, 13GM_DQ, ...
5                                                     {2}
6                                                     {2}
                              ...                        
2141                                                  {2}
2142                                                  {2}
2143                                                  {2}
2144                                                  {2}
2145                                                  {2}
Name: EpMismatches, Length: 2144, dtype: object

I’m using Python 3.11.0 and pandas==1.5.1

Answers:

Because set.add working inplace, None is expected. Here are alternatives:

epitope_charge_detail.apply(lambda set_: set_.union({2}))
epitope_charge_detail.apply(lambda set_: set_ | {2})
Answered By: jezrael
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.