Apply A Function To Pandas Dataframe With A Condition To Check For `nans`
I have Null and NaNs in one of the pandas DataFrame columns. I'd like to apply with a condition to check for NaN in the column and store the return from the function into a new col
Solution 1:
You can first filter for the rows you want, apply the function and then assign to the new column. Pandas will fill the missing rows with NaN. This is usually more efficient than running apply for each row.
import pandas as pd
from numpy import NaN
df = pd.DataFrame({'Col1': [1, 9, NaN],
'Col2': [1, 3, 5]})
defsample_func(v1, v2, token):
# call API
r = cl_apicall(v1, v2, token)
return r
# mock api calldefcl_apicall(v1, v2, token):
returnf"{v1},-{v2}-{token}"# Apply function#df['new_col'] = df.apply(lambda x: sample_func(x['Col1'], x['Col2'], 'xxxxxx'), axis = 1)
df['new_col'] = df[df['Col1'].isnull()].apply(lambda x: sample_func(x['Col1'], x['Col2'], 'xxxxxx'), axis = 1)
print(df)
Result
Col1 Col2 new_col
01.01NaN19.03NaN2NaN5 nan,-5.0-xxxxxx
Post a Comment for "Apply A Function To Pandas Dataframe With A Condition To Check For `nans`"