我有一個包含 1 年每周 OHLC 資料的資料框。我需要什么 ?
- 僅列出每個月的最后一個星期一的資料。例如,May 有 5 周,我想列出可能的上周一的資料,需要丟棄其余的。這是我嘗試過的代碼,我可以每周列出資料。我被困在這里了!任何幫助,將不勝感激!
import pandas as pd
import yfinance as yf
import datetime
from datetime import date, timedelta
periods=pd.date_range(start='2021-4-30',periods=60,freq='W')
start = periods[0].strftime('%Y-%m-%d')
end = periods[-1].strftime('%Y-%m-%d')
symbol="^NSEI"
df=yf.download(symbol,start,end,interval="1wk",index=periods)
uj5u.com熱心網友回復:
您可以使用 groupby( pd.Grouper() ) 按月分組并獲取最新記錄。
# reset index to flatten columns
df = df.reset_index()
# copy date column to label last monday of a month
df['last_monday_of_month'] = df['Date']
# groupby month and get latest record
df.groupby(pd.Grouper(freq='M', key='Date')).last().reset_index()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/468949.html
