如何仅从 python 中的数据框中查找上周一的数据?
How to find the last monday's data only from a dataframe in python?
我有一个包含 1 年每周 OHLC 数据的数据框。
我需要什么?
- 仅列出每个月最后一个星期一的数据。例如,5 月有 5 周,我想列出 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)
可以使用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()
我有一个包含 1 年每周 OHLC 数据的数据框。 我需要什么?
- 仅列出每个月最后一个星期一的数据。例如,5 月有 5 周,我想列出 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)
可以使用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()