python - R-Python : Getting Monthly, 每周索引点

标签 python r pandas xts

在 R 的 xts 包中有一个名为 endpoints 的函数,它给定一个 xts 对象将返回一个索引,用于返回给定月份、星期或任何用户指定的频率。如何用 python 在 pandas 中做到这一点?

回复:

endpoints(xts.object, "frequency")

python :

from matplotlib.pylab import *
from pandas.io.data import DataReader
from datetime import datetime
symbols = ["SPY","IEF"]
data_holder = DataReader(symbols,  "yahoo",datetime(2001,1,1))
adj_close = data_holder["Adj Close"] #adjusted close data
adj_close = adj_close.dropna() #drop NAs
adj_close.head() #inspect elements

我知道在 python 中使用 "M" 作为参数的重采样函数会给我每月的数据。但是有没有一种方法可以获取一个索引数组,以便这些索引中的每一个都引用数据框中的一行,即月末日期?

这是一个具体的例子,我正在使用伪代码:

month_ends = adj_close.someFunction("months") #gives me the index of each month ends
month_ends.head()

[22,41,62..etc]

adj_close[month_ends,] #should give me the same thing as resampled("M")

最佳答案

[0, 1, ...] 作为值创建一个序列,然后调用 resample:

s = pd.Series(np.arange(adj_close.shape[0]), index=adj_close.index)
locs = s.resample("M", how="max")
print locs

输出是:

Date
2002-07-31      0
2002-08-31     22
2002-09-30     42
2002-10-31     65
2002-11-30     85
2002-12-31    106
2003-01-31    127
2003-02-28    146
2003-03-31    167
2003-04-30    188
2003-05-31    209
2003-06-30    230
2003-07-31    252
2003-08-31    273
2003-09-30    294
...
2012-09-30    2561
2012-10-31    2582
2012-11-30    2603
2012-12-31    2623
2013-01-31    2644
2013-02-28    2663
2013-03-31    2683
2013-04-30    2705
2013-05-31    2727
2013-06-30    2747
2013-07-31    2769
2013-08-31    2791
2013-09-30    2811
2013-10-31    2834
2013-11-30    2844
Freq: M, Length: 137, dtype: int64

获取行数:

print adj_close.iloc[locs, :].head(10)

输出:

             IEF    SPY
Date                    
2002-07-31  55.49  73.01
2002-08-30  56.89  73.51
2002-09-30  59.08  65.80
2002-10-31  58.34  71.22
2002-11-29  56.93  75.61
2002-12-31  58.95  71.33
2003-01-31  58.50  69.58
2003-02-28  59.79  68.64
2003-03-31  59.56  68.79
2003-04-30  59.64  74.61

关于python - R-Python : Getting Monthly, 每周索引点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821525/

相关文章:

python - 如何获得 Pandas 系列的元素逻辑非?

python - 如何在Python中调用一个函数来运行由用户输入确定的不同数据集?

python - 根据spark中的移动和将批号添加到DataFrame

r - R中使用lappy时如何处理NA

r - 从 R 中的列表创建数据框

python - 取两个日期时间值或列的中值

python - 为什么 x <= x 为假?

python - 检查集合中的任何值

根据列名称的条件重命名列

python-3.x - Python Pandas - 根据字符串值解析 CSV 文件中的行