【问题标题】: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当值在每天 24 小时内至少一次超过阈值时,在每小时数据的 pandas 数据框中计算每年的天数
【发布时间】:2019-12-01 22:30:15
【问题描述】:

我有一个数据框 (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。也就是说,如果 obs value >= 1.0 在一天的 24 条记录(小时)中的任何一条中,则该 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

【问题讨论】:

  • 越来越近了。试过: daysperyr = df2.groupby(pd.Grouper(freq='Y'))['obs'].apply(lambda x: x[x >= threshold].count()).to_frame().reset_index()产量: 1927-12-31 0 6 1928-12-31 1 7 1929-12-31 0 8 1930-12-31 0 9 1931-12-31 0 10 1932-12-31 0 11 1933-12-31 0 12 1934-12-31 4 13 1935-12-31 0 14 1936-12-31 0 15 1937-12-31 0 16 1938-12-31 0 17 1939-12-31 0 18 1940-12-31 1 19 1941-12-31 0 20 1942-12-31 0

标签: python pandas dataframe datetime counting


【解决方案1】:

这将为您提供高于“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()

【讨论】:

    【解决方案2】:

    这将为您提供每年至少有一次观察超过阈值的天数:

    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
    ...
    

    【讨论】:

      【解决方案3】:

      因为一天中的时间或同一天有多少可能再次发生都无关紧要。你应该瞄准

      treshold=1.0
      (df2.obs.resample('D').max()>=treshold).resample('Y').sum()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-12
        • 1970-01-01
        • 2019-08-13
        • 2023-03-06
        • 2013-10-15
        • 1970-01-01
        • 1970-01-01
        • 2016-09-10
        相关资源
        最近更新 更多