[英]How to add new columns at the end of a dataframe that contains hourly mean values and corresponding number of counts for each mean value per hour.
[英]Counting number of days per year in a pandas dataframe of hourly data when value exceeds a threshold at least once in 24 hour day
我有一個數據框(df2),其中包含從 1929 年到 2016 年的 24 小時數據[datetime (yy/mm/dd HH:MM)]
和[obs (float)]
。
樣本:
datetime obs
1/1/1929 0:00 -0.051
1/1/1929 1:00 0.285
1/1/1929 2:00 0.62
1/1/1929 3:00 0.955
1/1/1929 4:00 1.138
1/1/1929 5:00 1.23
1/1/1929 6:00 1.169
1/1/1929 7:00 0.925
1/1/1929 8:00 0.62
1/1/1929 9:00 0.285
1/1/1929 10:00 0.01
1/1/1929 11:00 -0.142
1/1/1929 12:00 -0.081
1/1/1929 13:00 0.193
1/1/1929 14:00 0.559
1/1/1929 15:00 0.955
1/1/1929 16:00 1.26
1/1/1929 17:00 1.352
1/1/1929 18:00 1.321
1/1/1929 19:00 1.108
1/1/1929 20:00 0.742
1/1/1929 21:00 0.376
1/1/1929 22:00 0.071
1/1/1929 23:00 -0.111
1/2/1929 0:00 -0.142
...
12/31 2016 23:00 1.02
我想確定數據框中每年obs value
>= 某個閾值的天數,例如 >=1.0。 也就是說,如果一天中的任何 24 條記錄(小時)中的obs value >= 1.0
,則該天的計數day=1
或 true。 然后我想計算count=1
或 true 時每年的天數並獲得一個新的數據框:
year days
1929 5
1930 2
...
2016 10
我是 Python 新手,只是嘗試通過 Google 找到的代碼。
daysperyr = df2.groupby(pd.Grouper(freq='Y'))['obs'].count().to_frame().reset_index()
這只是每年提供數量 obs
0 1929-12-31 8760
1 1930-12-31 8760
2 1931-12-31 8760
3 1932-12-31 8784
4 1933-12-31 8760
這將為您提供每年至少有一次觀察超過閾值的天數:
days = df[df['obs'] > threshold]['datetime'].dt.date.unique()
years = pd.to_datetime(days).to_series() \
.groupby(pd.Grouper(freq='Y')) \
.count()
如果你想從years.index
月份和日期:
years.index = years.index.year
結果(隨機數據):
1929 121
1930 116
1931 126
1932 109
1933 123
1934 122
...
這將為您提供高於“0”的每天觀察次數(您可以將 0 更改為任何數字)
df2 = df[df['obs']>0].groupby([df['datetime'].dt.year, df['datetime'].dt.date]).count().drop(columns = 'datetime')
然后我們可以使用它來查看每年有多少天:
df2.groupby(level=0).size()
因為在一天中的時間,或者在同一天有多少可能的再次發生並不重要。 你應該瞄准
treshold=1.0
(df2.obs.resample('D').max()>=treshold).resample('Y').sum()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.