2013-01-14 31 views
1

我有很多与计算rollng_mean当缺失值:使用遗漏值pandas.rolling_mean

import datetime as dt 
import pandas as pd 
import pandas.io.data as web 

stocklist = ['MSFT', 'BELG.BR'] 

# read historical prices for last 11 years 
def get_px(stock, start): 
    return web.get_data_yahoo(stock, start)['Adj Close'] 

today = dt.date.today() 
start = str(dt.date(today.year-11, today.month, today.day)) 

px = pd.DataFrame({n: get_px(n, start) for n in stocklist}) 
px.ffill() 
sma200 = pd.rolling_mean(px, 200) 

得到以下结果:

In [14]: px 
Out[14]: 
<class 'pandas.core.frame.DataFrame'> 
DatetimeIndex: 2836 entries, 2002-01-14 00:00:00 to 2013-01-11 00:00:00 
Data columns: 
BELG.BR 2270 non-null values 
MSFT  2769 non-null values 
dtypes: float64(2) 

In [15]: sma200 
Out[15]: 
<class 'pandas.core.frame.DataFrame'> 
DatetimeIndex: 2836 entries, 2002-01-14 00:00:00 to 2013-01-11 00:00:00 
Data columns: 
BELG.BR 689 non-null values 
MSFT  400 non-null values 
dtypes: float64(2) 

任何想法,为什么大多数sma200 rolling_mean值的失踪,如何获得完整列表?

回答

3

px.ffill()返回新的DataFrame。要修改px本身,请使用inplace = True

px.ffill(inplace = True) 
sma200 = pd.rolling_mean(px, 200) 
print(sma200) 

产生

Data columns: 
BELG.BR 2085 non-null values 
MSFT  2635 non-null values 
dtypes: float64(2) 
2

如果您打印sma200,您可能会发现很多空值或缺失值。这是因为对于rolling_mean,默认情况下非空值的阈值高。

尝试使用

sma200 = pd.rolling_mean(px, 200, min_periods=2) 

pandas docs

min_periods:非空数据点的阈值要求(否则结果是NA)

您也可以尝试如果数据集缺少许多点,则更改窗口的大小。

+0

好,谢谢。任何想法为什么填充没有解决这个问题? – ronnydw

+1

你需要在原地使用它,在调用'ffill'时通过'inplace = True'。 – jozzas