首页 > 解决方案 > 计算 pandas 末尾数据的百分比

问题描述

我需要计算给定 n 天内收盘价的盈亏百分比。df 是数据框。收盘价是收盘价

def profit_loss(days):
    last = df[-1:]['Close Price']
    begin = df[-days:-(days-1)]['Close Price']
    return ((last-begin)/last)*100

该函数应该给出所需的百分比。如果给定天数,该函数取最后一天的收盘价和最后 n 天的收盘价并计算盈亏百分比。我的输出给了我 NaN 作为输出

profit_loss(7)

输出是;

487   NaN
493   NaN
Name: Close Price, dtype: float64

预期输出为-0.0102。最近 7 天的收盘价数据为

[970.20,981.75,979.95,980.50,980.45,975.35,979.10]

标签: pythonpandasdata-sciencepercentage

解决方案


我相信您获得NaN输出值的原因是因为lastandbegin变量是 type Series。尝试添加.item(),这将返回float值。

last = df[-1:]['Close Price'].item()
begin = df[-days:-(days-1)]['Close Price'].item()

推荐阅读