首页 > 解决方案 > 通过 pandas 时间戳索引计算斜率

问题描述

我有以下数据集:

dates       A   B   C
2005-01-01  1.0 2.0 1.0
2005-01-02  2.0 1.0 1.0
2005-01-04  3.0 0.0 1.0

我想根据时间戳索引计算斜率。这应该是结果:

slope:
A 0.4
B -0.7
C -0.1

我试过这个解决方案:

slope = df.apply(lambda x: np.polyfit(df.index), x, 1)[0])

但它返回一个错误:

TypeError: float() argument must be a string or a number, not 'Timestamp'

任何帮助将不胜感激。

标签: pythonpandas

解决方案


a) 不要apply()将多项式拟合到“时间戳”字符串列,仅拟合到浮点列 A、B、C。所以要么创建dates索引,要么不将它包含在传递给 apply() 的列中。

使dates列成为您的索引

df.set_index('dates', inplace=True)

              A    B    C
dates                    
2005-01-01  1.0  2.0  1.0
2005-01-02  2.0  1.0  1.0
2005-01-04  3.0  0.0  1.0

b)现在关于修复apply()呼叫:

  • 你缺少第二个括号,你需要一个尾随...), axis=1来按列应用你的函数。
  • 此外,由于我们df.index现在更改为日期而不是自动编号的整数 0,1,2,因此您需要将明确的整数范围传递给polyfit().

解决方案:

#pd.options.display.float_format = '{:.3f}'.format
#pd.options.display.precision = 3
#np.set_printoptions(floatmode='fixed', precision=3, suppress=True)

df.apply(lambda x: np.polyfit(range(len(x)), x, 1), axis=1)

dates
2005-01-01    [-1.9860273225978183e-16, 1.3333333333333333]
2005-01-02        [-0.5000000000000004, 1.8333333333333341]
2005-01-04        [-0.9999999999999998, 2.3333333333333335]

(注意:我没有成功尝试设置 np 和 pd 显示选项来抑制 polyfit 返回的对象上不需要的 dps 和科学记数法。你可以自己弄清楚那部分。]


这是使您的示例可重现的样板:

import numpy as np
import pandas as pd
from io import StringIO

df = """dates       A   B   C
2005-01-01  1.0 2.0 1.0
2005-01-02  2.0 1.0 1.0
2005-01-04  3.0 0.0 1.0"""

df = pd.read_csv(StringIO(df), sep=r'\s+', parse_dates=['dates'])

推荐阅读