Working function fails to work within apply (produces "TypeError: 'int' object is not iterable")

Question:

I’m relatively new to python and pandas. I came across the following issue/problem.

Below, when I use the test_fnc on the series it works, but when I apply it on the series via the series.apply(test_fnc) method, I get "TypeError: 'int' object is not iterable" error.

Code:

import pandas as pd
series = pd.Series([1,2,4,777,5])
print(series)
test_fnc = lambda u: [-x if x==777 else x for x in u]
print(test_fnc(series))
series.apply(test_fnc)

Output:

0      1
1      2
2      4
3    777
4      5
dtype: int64
[1, 2, 4, -777, 5]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-77e41380f6db> in <module>
      4 test_fnc = lambda u: [-x if x==777 else x for x in u]
      5 print(test_fnc(series))
----> 6 series.apply(test_fnc)
Asked By: Musa H. Asyali

||

Answers:

You should not iterate in the function, apply is already doing that.

Instead define the function as: test_fnc = lambda x: -x if x==777 else x

test_fnc = lambda x: -x if x==777 else x

series.apply(test_fnc)

output:

0      1
1      2
2      4
3   -777
4      5
dtype: int64

If this is really the function to apply, use vectorial code (in place modification):

series.loc[series==777] *= -1

or for a new series:

new = series.mask(series==777, -series)
Answered By: mozway
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.