![](/img/trans.png)
[英]How to extract and group values from a Pandas Dataframe column based on the spread of the values
[英]How to extract values from a dataframe based on dates?
我有一個 DataFrame(見下圖),其中包含我想檢索幾個值的每日值。 我想檢索:每月平均值、每月最小值、每月最大值、每年最小值、年數等。目前我正在重新采樣 DataFrame 以檢索這些值(參見下面的代碼),但必須有更好的方法。
T_monthly=pd.DataFrame() # Create dataframe for monthly temperatures
T_monthly['Basse']=temp_basse.iloc[:,3].resample("M").mean() # Add Basse
T_monthly['Basse_min']=temp_basse.iloc[:,3].resample("M").min()
T_monthly['Basse_max']=temp_basse.iloc[:,3].resample("M").max()
T_monthly['Kedougou']=temp_kedougou.iloc[:,3].resample("M").mean() # Add Kedougou
T_monthly['Kedougou_min']=temp_kedougou.iloc[:,3].resample("M").min()
T_monthly['Kedougou_max']=temp_kedougou.iloc[:,3].resample("M").max()
T_yearly=pd.DataFrame() # Create dataframe for yearly temperatures
T_yearly['Basse_min']=temp_basse.iloc[:,3].resample("Y").min()
T_yearly['Basse_max']=temp_basse.iloc[:,3].resample("Y").max()
T_yearly['Kedougou_min']=temp_kedougou.iloc[:,3].resample("Y").min()
T_yearly['Kedougou_max']=temp_kedougou.iloc[:,3].resample("Y").max()
最好我想要一個 function ,我可以在其中輸入一個日期,例如 2014, 2 (Y, M) 並檢索所有必要的值,而無需重新采樣到新的 DataFrames。 例如:
輸入: (2014, 2)
output:[月平均值、月最小值、月最大值、年最小值、年最大值]
目前我的函數使用數據幀的索引號(見下文)。 但是,如果我想輸入某個日期,我首先需要找到相應的索引號。
T_monthly.iloc[i, 3]
提前致謝!
在 Sowjanya R Bhat 的建議之后又添加了兩列,包含 ['year'] 和 ['month']
df['year'] = pd.DatetimeIndex(df['date']).year
df['month'] = pd.DatetimeIndex(df['date']).month
接下來選擇數據:
df.loc[(df['year'] == year) & (df['month'] == month)].iloc[:,3]
不完全是我想要的(基於索引),但非常適合使用我編寫的函數遍歷數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.