将Pandas系列与同一系列划分为一个位置

时间:2016-10-08 17:18:49

标签: python pandas

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

当我运行此代码时:

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.向我展示。

2 个答案:

答案 0 :(得分:0)

问题是,当你执行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]是第一行

答案 1 :(得分:0)

您可以除以以下值:

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

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

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

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