Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I’m relatively new to python and pandas. I came across the following issue/problem, any help will be appreciated..

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading