【问题标题】:Using numpy, how do you calculate snowfall per month?使用 numpy,你如何计算每月的降雪量?
【发布时间】:2020-10-31 20:27:41
【问题描述】:

我有一个数据集,其中包含一年内每天的降雪记录。日期变量的格式为 YYYYMMDD。

Date      Snow
20010101  0
20010102  10
20010103  5
20010104  3
20010105  0
...
20011231  0

实际数据在这里

https://github.com/emily737373/emily737373/blob/master/COX_SNOW-1.csv

我想计算每个月下雪的天数。我知道如何用 pandas 做到这一点,但对于一个学校项目,我只需要使用 numpy 来做。我也不能导入日期时间,只能使用 numpy 来完成。

输出应该是这种形式

    Month     # days snowed
    January   13   
    February  19
    March     20
    ...
    December  15

我的问题是我如何只计算下雪天数(基本上当雪变量不为 0 时)而不必每个月单独计算?

【问题讨论】:

    标签: python arrays numpy snow


    【解决方案1】:

    我希望你可以使用一些内置的包,比如datetime,因为它在处理日期时间对象时很有用。

    import numpy as np
    import datetime as dt
    
    df = np.genfromtxt('test_files/COX_SNOW-1.csv', delimiter=',', skip_header=1, dtype=str)
    
    date = np.array([dt.datetime.strptime(d, "%Y%m%d").month for d in df[:, 0]])
    snow = df[:, 1].copy().astype(np.int32)
    
    has_snowed = snow > 0
    
    for month in range(1, 13):
        month_str = dt.datetime(year=1, month=month, day=1).strftime('%B')
        how_much_snow = len(snow[has_snowed & (date == month)])
        print(month_str, ':', how_much_snow)
    

    我将数据加载为str,因此我们保证以后可以将Date 列解析为日期。这就是为什么我们还需要将snow 列显式转换为int32,否则> 比较将不起作用。

    输出如下:

    January : 13
    February : 19
    March : 20
    April : 13
    May : 8
    June : 9
    July : 2
    August : 7
    September : 9
    October : 19
    November : 16
    December : 15
    

    让我知道这是否对您有用,或者如果您有任何其他问题。

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 1970-01-01
      • 2023-01-26
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多