<分区>
我有 python for finance 一书中的以下代码。但是来自 numpy 的 round 函数导致了类似“return round(decimals, out)
类型错误:round() 最多接受 2 个参数(给定 3 个)”
谁知道我做错了什么?
import numpy as np
import pandas as pd
import pandas.io.data as web
sp500 = web.DataReader('^GSPC', data_source='yahoo',
start='1/1/2000', end='4/14/2014')
sp500.info()
sp500['Close'].plot(grid=True, figsize=(8, 5))
sp500['42d'] = np.round(pd.rolling_mean(sp500['Close'], window=42), 2)
根据错误消息,似乎在 numpy 1.11.0
中,舍入函数如下所示:
try:
round = a.round
except AttributeError:
return _wrapit(a, 'round', decimals, out)
return round(decimals, out)
看起来 pandas.Series.round
只需要两个参数(self
,precision
),但是 numpy
向它传递了一个额外的参数,out
。据推测,这是 pandas
或 numpy
中的错误或 API 更改。
我可以看到两个简单的解决方法。第一种是直接使用 Series.round()
函数:
sp500['42d'] = pd.rolling_mean(sp500['Close'], window=42).round(2)
另一种选择是将 numpy.round
函数应用于底层 numpy 数组:
sp500['42d'] = np.round(pd.rolling_mean(sp500['Close'], window=42).values, 2)
编辑:看起来这是一个已知问题。参见 the pandas
github tracker, issue #12644 .