[英]Change Date Index dtype from object to datetime for monthly basis visualisation
我正在研究一個看起來像這樣的數據集
Index Month Day Year Temperature in Fahrenheit
0 1 1 2000 77.8
1 1 2 2000 79.3
2 1 3 2000 78.6
3 1 4 2000 78.6
4 1 5 2000 81.1
... ... ... ... ...
7299 12 27 2019 79.3
7300 12 28 2019 80.7
7301 12 29 2019 80.1
7302 12 30 2019 77.5
7303 12 31 2019 74.3
列的類型如下:
Month int64
Day int64
Year int64
Temperature in Fahrenheit float64.
現在,問題陳述是我想將此數據轉換為月度數據,取該月日的平均值。 一個片段如下所示
Date
2000-01 78.241935
2000-02 76.510345
2000-03 80.496774
2000-04 84.100000
2000-05 84.841935
...
2019-08 82.912903
2019-09 81.620000
2019-10 84.287097
2019-11 84.236667
2019-12 81.635484
我希望日期索引(現在是對象類型)的格式為日期時間,以便我可以每月正確地可視化它們。
先感謝您。
pd.to_datetime
idx = pd.to_datetime(df[['Month', 'Day', 'Year']])
vals = df['Temperature in Fahrenheit'].to_numpy()
pd.Series(vals, idx)
2000-01-01 77.8
2000-01-02 79.3
2000-01-03 78.6
2000-01-04 78.6
2000-01-05 81.1
2019-12-27 79.3
2019-12-28 80.7
2019-12-29 80.1
2019-12-30 77.5
2019-12-31 74.3
dtype: float64
您可以通過resample
來跟進
pd.Series(vals, idx).resample('M').mean()
另一種方式,可能不如@piRSquared 短
df[['Month', 'Day', 'Year']]=df.iloc[:, 1:-1].apply(lambda x: x.astype(str))
df['Date']=pd.to_datetime(df.pop('Day').str.cat([df.pop('Month'),df.pop('Year')], sep=' '))
df.set_index('Date', inplace=True)#Set Date as index
df.groupby(df.index.date).agg(TemperatureinFahrenheit= ('TemperatureinFahrenheit','mean'))#Groupby date and mean
只是另一種方法:
data=df.groupby(['Year','Month']).apply(lambda x:x['Temperature in Fahrenheit'].sum()).reset_index()
data['Date']=data['Year']+'-'+data['Month']
data.drop(columns=['Year','Month'],inplace=True)
data['Date']=pd.to_datetime(data['Date'],format='%Y-%-m')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.