Python:季节的日期时间

2024-06-09 07:18:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将日期时间序列转换为季节,例如,3、4、5个月我想用2(春天)替换它们;6、7、8个月我想用3(夏天)等替换它们

所以,我有这个系列

id
1       2011-08-20
2       2011-08-23
3       2011-08-27
4       2011-09-01
5       2011-09-05
6       2011-09-06
7       2011-09-08
8       2011-09-09
Name: timestamp, dtype: datetime64[ns]

这是我一直试图使用的代码,但没有用。

# Get seasons
spring = range(3, 5)
summer = range(6, 8)
fall = range(9, 11)
# winter = everything else

month = temp2.dt.month
season=[]

for _ in range(len(month)):
    if any(x == spring for x in month):
       season.append(2) # spring 
    elif any(x == summer for x in month):
        season.append(3) # summer
    elif any(x == fall for x in month):
        season.append(4) # fall
    else:
        season.append(1) # winter

以及

for _ in range(len(month)):
    if month[_] == 3 or month[_] == 4 or month[_] == 5:
        season.append(2) # spring 
    elif month[_] == 6 or month[_] == 7 or month[_] == 8:
        season.append(3) # summer
    elif month[_] == 9 or month[_] == 10 or month[_] == 11:
        season.append(4) # fall
    else:
        season.append(1) # winter

这两种解决方案都不起作用,特别是在第一个实现中,我收到一个错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

而在第二个是一个有错误的大列表。有什么想法吗?谢谢


Tags: orinforlenanyrangeelseseason
3条回答

也可以使用字典映射。

  1. 创建一个将一个月映射到一个季节的字典:

    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. 用它把月份转换成季节

    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
    

性能:比较快

In [35]: %timeit df.id.dt.month.map(month_to_season) 
1000 loops, best of 3: 422 µs per loop

我想这能行。

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)

可以使用简单的数学公式将一个月压缩为一个季节,例如:

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

因此对于您的用例:

>>> temp2.apply(lambda dt: (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

或者使用向量运算(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

相关问题 更多 >