pandas 熊猫在我的数据中按第一天重新采样

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29871564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:15:33  来源:igfitidea点击:

Pandas resample by first day in my data

pythonpandasdataframeresampling

提问by Amin

I have a Yahoo finance daily stock price imported in a pandas dataframe. I want to use .resample()to convert it to the monthly stock price by taking the price of the first QUOTED daily price of each month.

我在Pandas数据框中导入了雅虎财经每日股票价格。我想.resample()通过获取每个月第一个 QUOTED 每日价格的价格将其转换为每月股票价格。

.resample('MS', how='first')

returns the correct price of each month butit changes the index to the first day of the month while in general the first day of a month for a quoted price maybe 2nd or 3rd of the month because of holidays and weekends.

返回每个月的正确价格,它会将指数更改为该月的第一天,而由于节假日和周末,通常一个月的第一天报价可能是该月的第 2 天或第 3 天。

How can I use resample()by only resampling the existing dates and not changing them?

如何resample()仅通过重新采样现有日期而不更改它们来使用?

回答by Andy Hayden

I think what you wantis BMS(business month start):

我想你想要的BMS(营业月开始):

.resample('BMS').first()

Note: Prior to pandas 0.18 this was done using the deprecated howkwarg:

注意:在 pandas 0.18 之前,这是使用已弃用的howkwarg完成的:

.resample('BMS', how='first')


An alternative would be to groupby month and take the first with a plain ol' groupby (and e.g. use nthto get the first entry in each group):

另一种选择是 groupby 月份并使用普通的 ol' groupby 取第一个(例如使用nth获取每个组中的第一个条目):

.groupby(pd.Grouper(freq='M')).nth(0)

Note: Prior to pandas 0.21 this was done using the deprecated TimeGrouper:

注意:在 pandas 0.21 之前,这是使用已弃用的TimeGrouper

.groupby(pd.TimeGrouper('M')).nth(0)