[英]how to create a pandas data frame with the first days and the last days of Months
[英]finding first and last available days of a month in pandas
我有一個從 2007 年到 2017 年的熊貓數據框。數據是這樣的:
date closing_price
2007-12-03 728.73
2007-12-04 728.83
2007-12-05 728.83
2007-12-07 728.93
2007-12-10 728.22
2007-12-11 728.50
2007-12-12 728.51
2007-12-13 728.65
2007-12-14 728.65
2007-12-17 728.70
2007-12-18 728.73
2007-12-19 728.73
2007-12-20 728.73
2007-12-21 728.52
2007-12-24 728.52
2007-12-26 728.90
2007-12-27 728.90
2007-12-28 728.91
2008-01-05 728.88
2008-01-08 728.86
2008-01-09 728.84
2008-01-10 728.85
2008-01-11 728.85
2008-01-15 728.86
2008-01-16 728.89
如您所見,每個月都缺少一些日子。 我想取每個月的第一個和最后一個“可用”天數,並計算它們的收盤價的差異,並將結果放入一個新的數據框中。 例如,第一個月的天數為 2007-12-03 和 2007-12-28,收盤價為 728.73 和 728.91,因此結果為 0.18。 我怎樣才能做到這一點?
您可以按月對 df 進行分組並應用一個函數來完成它。 注意to_period ,此函數將 DataFrame 從 DatetimeIndex 轉換為具有所需頻率的 PeriodIndex 。
def calculate(x):
start_closing_price = x.loc[x.index.min(), "closing_price"]
end_closing_price = x.loc[x.index.max(), "closing_price"]
return end_closing_price-start_closing_price
result = df.groupby(df["date"].dt.to_period("M")).apply(calculate)
# result
date
2007-12 0.18
2008-01 0.01
Freq: M, dtype: float64
首先確保它們是datetime
並已排序:
import pandas as pd
df['date'] = pd.to_datetime(df.date)
df = df.sort_values('date')
gp = df.groupby([df.date.dt.year.rename('year'), df.date.dt.month.rename('month')])
gp.closing_price.last() - gp.closing_price.first()
#year month
#2007 12 0.18
#2008 1 0.01
#Name: closing_price, dtype: float64
或者
gp = df.groupby(pd.Grouper(key='date', freq='1M'))
gp.last() - gp.first()
# closing_price
#date
#2007-12-31 0.18
#2008-01-31 0.01
gp = df.set_index('date').resample('1M')
gp.last() - gp.first()
# closing_price
#date
#2007-12-31 0.18
#2008-01-31 0.01
問題:獲取索引數據幀的第一個或最后一個日期
解決方案:重新采樣索引,然后提取數據。
lom = pd.Series(x.index, index = x.index).resample('m').last()
xlast = x[x.index.isin(lom)] # .resample('m').last() to get monthly freq
fom = pd.Series(x.index, index = x.index).resample('m').first()
xfirst = x[x.index.isin(fom)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.