Python 从Pandas面板中选择日期而不在项目上循环

Python 从Pandas面板中选择日期而不在项目上循环,python,pandas,Python,Pandas,我有很多在交易日没有对齐的股票数据。您可以使用代码:dataFrame.ix[dateSet]从pandas数据框中选择日期,但我想对面板做一些类似的操作,并在面板上循环并重新连接它们。所以某种Panel.ix[daterange]会很有用 def slicePanelOverTradingDates(panel = fpStockPanel, security = 'SPY'): # get the trading dates of the S&P starting with

我有很多在交易日没有对齐的股票数据。您可以使用代码:dataFrame.ix[dateSet]从pandas数据框中选择日期,但我想对面板做一些类似的操作,并在面板上循环并重新连接它们。所以某种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
支持多维选择,请参阅;这同样适用于
.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
[18]中的
:p=tm.makePanel()
In[19]:p
出[19]:
尺寸:3(项目)x 30(长轴)x 4(短轴)
项目轴:项目A至项目C
长轴:2000-01-03 00:00:00至2000-02-11 00:00:00
短_轴:A至D
在[20]:p.loc[:,'2000-1-4':'2000-1-31']
出[20]:
尺寸:3(项目)x 20(长轴)x 4(短轴)
项目轴:项目A至项目C
长轴:2000-01-04 00:00:00至2000-01-31 00:00:00
短_轴:A至D

太好了-这很有效,谢谢。使用原始问题的语法:tradingDates=DataReader('SPY','yahoo','2003-01-01')['Adj Close'].dropna().index然后是d.loc[:,tradingDates],您也可以选择其他字段,例如
面板.loc[项目,长轴,短轴]
;如果项目(或轴)是标签(而不是列表或idnexer),则结果的维度将被删除,例如,您将获得一个框架)