python - 从 Pandas 面板中选择日期而不循环遍历项目

标签 python pandas

我的面板上充满了股票数据,但这些数据在交易日上并不一致。您可以使用代码:dataFrame.ix[dateSet] 从 pandas DataFrame 中选择日期,但我想对面板执行类似的操作,并诉诸于循环面板并重新加入它们。因此某种 Panel.ix[daterange] 会很有用。

def slicePanelOverTradingDates(panel = fpStockPanel, security = 'SPY'):
    # get the trading dates of the S&P starting with the first date of the panel's adjusted close item
    validSPXDates = DataReader('SPY','yahoo',panel['Adj Close'].index[0].date()).index
    # take the dates that are valid in the stock panel that intersect with the S&P's dates   and makes sure they're in order
    panelDatesOnSPXDays = list(set(panel['Adj Close'].index).intersection(set(validSPXDates)))
    panelDatesOnSPXDays.sort()
    # remakes the panel sliced only over the correct dates
    panelFrame = {}
    for x in panel.items:
        panelFrame[x] = panel[x].ix[panelDatesOnSPXDays]
    finalPanel = pd.Panel(panelFrame)
    return finalPanel

最佳答案

.loc 支持多维选择,参见here ;这也适用于 .ix.iloc

In [18]: p = tm.makePanel()

In [19]: p
Out[19]: 
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 30 (major_axis) x 4 (minor_axis)
Items axis: ItemA to ItemC
Major_axis axis: 2000-01-03 00:00:00 to 2000-02-11 00:00:00
Minor_axis axis: A to D

In [20]: p.loc[:,'2000-1-4':'2000-1-31']
Out[20]: 
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 20 (major_axis) x 4 (minor_axis)
Items axis: ItemA to ItemC
Major_axis axis: 2000-01-04 00:00:00 to 2000-01-31 00:00:00
Minor_axis axis: A to D

关于python - 从 Pandas 面板中选择日期而不循环遍历项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20619332/

相关文章:

python - urllib 上缺少方法

python - 如何跟踪线性工作流程中的步骤

python - OpenCV unproject 2D 指向具有已知深度 `Z` 的 3D

python - skflow pandas数据集平均每2行

python - Pandas:如何从 CSV 文件中读取特定行

python - 删除 - 列中每一行中的字符,但仅当它们位于数字之后时

python - 使用反斜杠将字符串列表转换为正确的目录名称

python - python MYSQLConnection 中的游标关闭错误

python - 当列包含 `==` 而不是 `List` 时, Pandas 比较运算符 `Tuple` 无法按预期工作

python - “DataFrame”对象没有属性 'Hight'