Pandas version checks
-
[X] I have checked that this issue has not already been reported.
-
[X] I have confirmed this bug exists on the latest version of pandas.
-
[ ] I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import pandas as pd
pre_df = pd.DataFrame(...)
pre_df['row_with_nonetype'].apply(lambda x: func(x))
Issue Description
Because apply is checking the len(s) here:
....pandas/core/apply.py:1123), in SeriesApply.apply(self)
1120 return self.apply_str()
1122 # self.f is Callable
...
--> 907 index = default_index(len(s))
909 if id(index) in indexer_cache:
910 indexer = indexer_cache[id(index)]
when s
is NoneType it returns error.
Expected Behavior
No error
Installed Versions
Comment From: phofl
Please post a reproducible example
Comment From: alexprincel
Adding the exact error message observed would be helpful as well.
Comment From: Ali-Flt
I apologize, I believe my mistake was that I was trying to write a pandas Series into a pandas DataFrame's cell and the error put me off. The scenario was something like this:
def func(x):
try:
return x[1]
except Exception:
return x
df['new_col] = df['old_col']apply(lambda x: func(x))
Where df['old_col']
had pd.Series() in its cells, some of which were a pd.Series() with a single element = None and some others were a pd.Series() with a single element = tuple(...).
I used .item()
instead and it worked:
def func(x):
try:
return x.item()[1]
except Exception:
try:
return x[1]
except Exception:
try:
return x.item()
except Exception:
return x
df['new_col] = df['old_col']apply(lambda x: func(x))