我要订购以下季节,即1999年:冬天,春天,夏天,秋天,冬天,2000年,冬天,春天等
此刻我所拥有的东西很长而且不好:
import calendar
df['month_num'] = pd.DatetimeIndex(df.index).month
df['year_num'] = pd.DatetimeIndex(df.index).year
df['year_month_num'] = df.month_num + (df.year_num +- 1999)*12
year_month_num_to_season_num = {1:1,2:1,3:2,4:2,5:2,6:3,7:3,8:3,9:4,10:4,11:4,12:5,
13:5,14:5,15:6,16:6,17:6,18:7,19:7,20:7,21:8,22:8,23:8,24:9,
25:9,26:9,27:10,28:10,29:10,30:11,31:11,32:11,33:12,34:12,35:12,36:13,
37:13,38:13,39:14,40:14,41:14,42:15,43:15,44:15,45:16,46:16,47:16,48:17,
49:17,50:17,51:18,52:18,53:18,54:19,55:19,56:19,57:20,58:20,59:20,60:21,
61:21,62:21,63:22,64:22,65:22,66:23,67:23,68:23,69:24,70:24,71:24,72:25,
73:25,74:25,75:26,76:26,77:26,78:27,79:27,80:27,81:28,82:28,83:28,84:29,
85:29,86:29,87:30,88:30,89:30,90:31,91:31,92:31,93:32,94:32,95:32,96:33,
97:33,98:33,99:34,100:34,101:34,102:35,103:35,104:35,105:36,106:36,107:36,108:37,
109:37,110:37,111:38,112:38,113:38,114:39,115:39,116:39,117:40,118:40,119:40,120:41,
121:41,122:41,123:42,124:42,125:42,126:43,127:43,128:43,129:44,130:44,131:44,132:45,
133:45,134:45,135:46,136:46,137:46,138:47,139:47,140:47,141:48,142:48,143:48,144:49,
145:49,146:49,147:50,148:50,149:50,150:51,151:51,152:51,153:52,154:52,155:52,156:53,
157:53,158:53,159:54,160:54,161:54,162:55,163:55,164:55,165:56,166:56,167:56,168:57,
169:57,170:57,171:58,172:58,173:58,174:59,175:59,176:59,177:60,178:60,179:60,180:61,
181:61,182:61,183:62,184:62,185:62,186:63,187:63,188:63,189:64,190:64,191:64,192:65,
193:65,194:65,195:66,196:66,197:66,198:67,199:67,200:67,201:68,202:68,203:68,204:69,
205:69,206:69,207:70,208:70,209:70,210:71,211:71,212:71,213:72,214:72,215:72,216:73,
217:73,218:73,219:74}
df['season_ordinal'] = df.year_month_num.map(year_month_num_to_season_num)
答案 0 :(得分:1)
您的映射字典可以通过简单的字典理解来准确给出:
year_month_num_to_season_num = {i:(i+3)//3 for i in range(1,220)}
这使用整数除法。值部分需要一定数量的移位,因此前两个值是1
。