计算对数变化的替代方法产生不同的结构

2024-04-20 08:35:33 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释为什么第二种计算日志变化的方法会产生一个numpy数组,丢弃索引而不是DataFrame吗?如果我指定DataFrame,我会得到一个基于整数的索引。第一种方法根据需要工作。谢谢你的真知灼见

import numpy as np
import pandas as pd
import pandas_datareader as pdr
aapl = pdr.get_data_yahoo('AAPL')
close = pd.DataFrame(aapl['Close'])
change = np.log(close['Close'] / close['Close'].shift(1))
another_change = np.diff(np.log(close['Close']))

Tags: 方法importnumpylogdataframepandascloseas
1条回答
网友
1楼 · 发布于 2024-04-20 08:35:33

我找不到支持这个的文档,但是当Series输入的维数减少时,返回的类型似乎正在转换为ndarray。这种情况发生在diff而不是log

举个简单的例子:

x = pd.Series(range(5))

change = np.log(x / x.shift(1)) # Series of float64 of length 5

another_change = np.diff(np.log(x)) # array of float64 of length 4

我们可以观察到x / x.shift(1)仍然是一个5元素序列(即使元素0和1是NaNinf),所以np.log,它不降维,仍然会返回一个5元素的东西,它匹配x的维数

然而,np.diff确实减少了它应该返回的维度(根据doc

diff : ndarray The n-th differences. The shape of the output is the same as a except along axis where the dimension is smaller by n. [...]

下一句话出现在上面的numpy 1.13文档中,但不是1.12和更早版本:

[...] The type of the output is the same as that of the input.

所以输出的类型仍然是一个类似数组的结构,但是由于维数的减少,它可能不会被重新转换为一个序列(类似数组的输入)。至少在1.12和更早版本中

那是我最好的猜测

相关问题 更多 >