python - 计算 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]
解决方案
我相信您获得NaN
输出值的原因是因为last
andbegin
变量是 type Series
。尝试添加.item()
,这将返回float
值。
last = df[-1:]['Close Price'].item()
begin = df[-days:-(days-1)]['Close Price'].item()
推荐阅读
- node.js - 如何在用户点击节点通知程序之前保持通知状态?
- azure - 在 Azure 应用服务上使用 WebSocket 时的权衡?
- css - 如何在 Antd 的 Modal 中更改样式?
- reactjs - React 中的侧边栏条件渲染
- wordpress - Wordpress graphql(WPGraphQL)如何建立订阅
- logging - 如何获取服务容器日志并将其作为工件上传到 gitlab
- node.js - 在 mongodb 中更新嵌套对象数组的问题
- python - 用条件过滤熊猫df
- flutter - 与 ListView 中的每个其他项目重叠的项目
- python - Pycharm 安装插件后不会发生