【问题标题】:Dividing a Pandas series with the same series shifted one place将 Pandas 系列与同系列分开移动一位
【发布时间】:2016-10-08 17:18:48
【问题描述】:

我有一个熊猫系列,一个时间和一个价值。 我想计算每个值之间的变化。 像这样:当前值/先前值。

当我运行这段代码时:

print now.head(n=3)
print before.head(n=3)
delta = now.divide(before)
print delta.iloc[1]
print now.iloc[1] / before.iloc[1]

我得到这个结果:

DateTime
2014-01-08 09:27:00    623.53836
2014-01-08 09:28:00    623.54066
2014-01-08 09:32:00    623.53846
Name: close, dtype: float64
DateTime
2014-01-08 09:26:00    624.01000
2014-01-08 09:27:00    623.53836
2014-01-08 09:28:00    623.54066
Name: close, dtype: float64
1.0
1.00000368863

由于最后两个数字不同,我错过了什么?

现在和之前的系列是同一个系列,只是移动了一个位置。

更新:问题是pandas在分割时匹配的索引。幸运的是,pandas 有一个名为 .pct_change() 的内置函数,它完全符合我的要求。感谢 Steven G. 向我展示了这一点。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    问题是当你做delta = now.divide(before)它会匹配索引。所以 delta.iloc[1] 将是623.53836 / 623.53836 代表2014-01-08 09:27:00 索引上的划分

    当你使用整数位置 now.iloc[1] / before.iloc[1] 它不关心索引,所以它关心 623.54066 / 623.53836

    记住.iloc[1] 是第二行,.iloc[0] 是第一行

    【讨论】:

    • 我认为他的问题是为什么“delta.iloc[1]”和“now.iloc[1] / before.iloc[1]”不同
    • 这两个都返回一堆 1.0。
    • 格式没有区别。最后两个结果还是一样的:1.0 vs 1.00000368863
    • 这就解释了。现在我只需要弄清楚如何阻止它匹配索引。
    • @Nis 你想达到什么目的?百分比变化?
    【解决方案2】:

    你可以除以值:

    now['delta'] = now.values / before.values
    

    这当然会为您现在的数据框添加一个新列。

    或者,如果您想在自己的数据框中使用它,您可以编写:

    delta = now.copy()
    delta['delta'] = now.close.values / before.close.values
    delta.drop('close', 1, inplace=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 2015-09-02
      • 2021-11-22
      • 2019-03-08
      • 1970-01-01
      • 2019-02-25
      • 2023-01-25
      相关资源
      最近更新 更多