python - Python数据框 - 比较两个数据框之间的行
问题描述
我有一个数据框(我们称之为 A),它看起来像:
Date Open High Low Close Adj Close Volume
0 2010-01-04 9.1825 9.2350 9.0875 9.1025 9.1025 1172000
1 2010-01-05 9.1025 9.1350 9.0550 9.1000 9.1000 658000
2 2010-01-06 9.0750 9.1150 9.0450 9.0625 9.0625 617600
3 2010-01-07 9.0250 9.0600 8.9425 9.0100 9.0100 913600
4 2010-01-08 8.9750 9.0375 8.9250 9.0375 9.0375 1271200
我正在计算 t 日收盘价大于 t-1 日收盘价的总天数:
total_positive_days = (asset.Close > asset.Close.shift(1)).sum()
我有另一个数据框(称为 sp_500),我想为它计算 A 的第 t 天的回报(关闭 A t - 关闭 A t-1)/关闭 A t-1 大于回报的总天数sp_500 (关闭 sp_500 t - 关闭 sp_500 t-1)/关闭 sp_500 t-1
我怎样才能做到这一点?
解决方案
您可以在日期上设置索引,然后在数据框中创建新列
A['return'] = A.close - A.close.shift(1) / A.close.shift(1)
sp_500['return'] = sp_500.close - sp_500.close.shift(1) / sp_500.close.shift(1)
然后根据日期合并
推荐阅读
- swift - 动画 UIView 总是在左上角,即使中心在其他地方
- raspberry-pi - 覆盆子如何在不知道纬度/经度的情况下找到其本地时区
- php - 在主题中加载特定的 WooCommerce 模板
- bash - 将代码拆分为文件
- unity3d - 为什么我的搅拌机 .fbx 文件没有导出到 Unity?
- asp.net-core - 如何在 Asp net core 3.1 中通过身份服务器 4 中的用户 ID 获取 access_token、刷新令牌
- java - 导入比主 gradle 项目文件高一级的额外项目
- c# - 是否可以在 C# 中为 KeyValuePairs 的 LinkedList 创建序列化代理?
- r - R循环使用data.table标准化变量
- postgresql - 如何更改露天开始目录?