Below is the function I made in order to return last numeric value :
def DerniereValeur(DF):
for i in range(1,100):
print(DF[-i])
if DF[-i].isnumeric():
ValeurARetourner = DF[-i]
break
return ValeurARetourner
Where DF looks like :
FirstExample | SecondExample |
---|---|
28.32 | 18.32 |
60.2751 | NaN |
Output excepted
DerniereValeur(FirstExample)
> Returns 60.2751
DerniereValeur(SecondExample)
> Returns 18.32
Error Message
AttributeError: 'float' object has no attribute 'isnumeric'
Debug infos
Thrown on DerniereValeur(FirstExample)
line : if DF[-i].isnumeric():
Where DF[-i]=60.2751
DF
Unnamed: 2 100
Unnamed: 3 100.5425
Unnamed: 4 101.01144
Unnamed: 5 101.97366
Unnamed: 6 102.27216
Unnamed: 1257 60.97918
Unnamed: 1258 60.568195
Unnamed: 1259 61.285896
Unnamed: 1260 61.92188
Unnamed: 1261 60.62751
CodePudding user response:
Instead of passing columns one by one by the function, you could stack
the DataFrame and use groupby.last
to get the last numeric values of each column in one go:
out = df.stack().reset_index(level=1).groupby('level_1').last().rename_axis(None).T
Output:
FirstExample SecondExample
0 60.2751 18.32
For a single column DataFrame, we could use dropna
(to get rid of trailing NaNs) tail
(for the last value):
df[['SecondExample']].dropna().tail(1)
Output:
SecondExample
0 18.32
CodePudding user response:
You could use dropna
on the column of interest and then take the last remaining value in the column, checking for IndexError
in case there are no non-NaN values:
def DerniereValeur(DF):
try:
return DF.dropna().iat[-1]
except IndexError:
return np.NaN
df = pd.DataFrame({
'FirstExample': [28.32, 60.2751],
'SecondExample': [18.32, np.NaN],
'ThirdExample': [np.NaN, np.NaN]
})
DerniereValeur(df['FirstExample'])
DerniereValeur(df['SecondExample'])
DerniereValeur(df['ThirdExample'])
Output:
60.2751
18.32
nan