python - 通过 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'
任何帮助将不胜感激。
解决方案
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'])
推荐阅读
- xcode - 如何设置 Bundle Ids、App Identifiers 和 Provisioning Profiles 以发布使用 SwiftUI 和 XCode 制作的 WatchOs 应用程序?
- javascript - 粘性副标题在滚动时闪烁
- python - 如何使用 python 将数据从一个源移动到另一个源?
- arrays - 在 laravel 中按数量进行 foreach
- python - 如何修复 ValueError: Input 0 is in compatible with layer CNN: expected shape=(None, 35), found shape=(None, 31)
- flutter - Command CompileSwift 因非零退出代码权限处理程序插件而失败
- graphql - 从 Mule 4 使用 graphQL API
- php - 用n个小数比较两个浮点数的哪种方法在PHP中最有效?
- mysql - 已将握手入队后无法将握手入队
- block - 阻止来自 D-Link 的网站