I have a df
where a particular col has several null values. I want to extract the first non null value.
print(df.kst_erloes_stpfl.to_list())
[nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 'WH042700', 90510000, 90510000]
import numpy as np
def not_na(array):
return ~np.isnan(array)
def first_not_na_value(array):
return list(filter(not_na, array))[0]
first = first_not_na_value(df.kst_erloes_stpfl)
print(first)
However, I get this error:
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
What else can I try to extract the first non null value?
CodePudding user response:
The easiest way is to use pandas built-in function dropna:
import numpy as np
import pandas as pd
values = [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
np.nan, np.nan, np.nan, np.nan, np.nan, 'WH042700', 90510000, 90510000]
df = pd.DataFrame(values)
first_non_na = df.dropna().iloc[0,0]
print(first_non_na)