首页 > 解决方案 > 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

我怎样才能做到这一点?

标签: pythondataframe

解决方案


您可以在日期上设置索引,然后在数据框中创建新列

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)

然后根据日期合并


推荐阅读