Python: Datetime to season

后端 未结 3 1569
青春惊慌失措
青春惊慌失措 2020-11-30 10:34

I want to convert a date time series to season, for example for months 3, 4, 5 I want to replace them with 2 (spring); for months 6, 7, 8 I want to replace them with 3 (summ

3条回答
  •  我在风中等你
    2020-11-30 10:56

    You can use a simple mathematical formula to compress a month to a season, e.g.:

    >>> [(month%12 + 3)//3 for month in range(1, 13)]
    [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 1]
    

    So for your use-case using vector operations (credit @DSM):

    >>> (temp2.dt.month%12 + 3)//3
    1    3
    2    3
    3    3
    4    4
    5    4
    6    4
    7    4
    8    4
    Name: id, dtype: int64
    

提交回复
热议问题