gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:40:26 26 4
gpt4 key购买 nike

我的面板上充满了股票数据,但这些数据在交易日上并不一致。您可以使用代码: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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com