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

2024-09-27 23:27:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的面板上满是股票数据,交易日不一致。您可以使用以下代码:数据帧.ix[dateSet]从pandas数据框中选择日期,但我想用panels做类似的事情,并在面板上循环并重新连接它们。所以某种程度上展板.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

Tags: ofthe数据in面板dateindexwith
1条回答
网友
1楼 · 发布于 2024-09-27 23:27:02

.loc支持多维选择,请参见here;这同样适用于.ix和{}

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

相关问题 更多 >

    热门问题