'Building a function which return the last numeric value of a DF returns : 'float' object has no attribute 'isnumeric'
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
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nick |
