构建一个 return DF returns 的最后一个数值的函数:'float' 对象没有属性 'isnumeric'

Building a function which return the last numeric value of a DF returns : 'float' object has no attribute 'isnumeric'

下面是我为了 return 最后一个数值而创建的函数:

def DerniereValeur(DF):
    for i in range(1,100):
        print(DF[-i])
        if DF[-i].isnumeric():
            ValeurARetourner = DF[-i]
            break
    return ValeurARetourner

DF 的样子:

FirstExample SecondExample
28.32 18.32
60.2751 NaN

输出除外

DerniereValeur(FirstExample)
> Returns 60.2751
DerniereValeur(SecondExample)
> Returns 18.32

错误信息

AttributeError: 'float' object has no attribute 'isnumeric'

调试信息

投掷于 DerniereValeur(FirstExample)

行:if DF[-i].isnumeric():

哪里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

您可以在感兴趣的列上使用 dropna,然后取该列中的最后一个剩余值,检查 IndexError 以防没有 non-NaN 值:

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'])

输出:

60.2751
18.32
nan