Python: Datetime to season

后端 未结 3 1552
青春惊慌失措
青春惊慌失措 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
    
    0 讨论(0)
  • 2020-11-30 10:56

    I think this would work.

    while True:
    date=int(input("Date?"))
    season=""
    if date<4:
        season=1
    elif date<7:
        season=2
    elif date<10:
        season=3
    elif date<13:
        season=4
    else:
        print("This would not work.")
    print(season)
    
    0 讨论(0)
  • 2020-11-30 11:03

    It's, also, possible to use dictionary mapping.

    1. Create a dictionary that maps a month to a season:

      In [27]: seasons = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 1]
      
      In [28]: month_to_season = dict(zip(range(1,13), seasons))
      
      In [29]: month_to_season 
      Out[29]: {1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, 9: 4, 10: 4, 11: 4, 12: 1}
      
    2. Use it to convert the months to seasons

      In [30]: df.id.dt.month.map(month_to_season) 
      Out[30]: 
      1    3
      2    3
      3    3
      4    4
      5    4
      6    4
      7    4
      8    4
      Name: id, dtype: int64
      

    Performance: This is fairly fast

    In [35]: %timeit df.id.dt.month.map(month_to_season) 
    1000 loops, best of 3: 422 µs per loop
    
    0 讨论(0)
提交回复
热议问题