九州编程
其他解决方案解决了您的问题,但实际上对于这种类型的计算,您应该使用.map或pd.cut样本数据:import numpy as npimport pandas as pddf = pd.DataFrame({'Month': np.random.randint(1,13,10)}).mapd = {1:1, 2:1, 3:2, 4:2, 5:3, 6:4, 7:5, 8:5, 9:6, 10:6, 11:7, 12:7}df['Mapped'] = df.Month.map(d)# Month Mapped#0 3 2#1 3 2#2 7 5#3 2 1#4 4 2#5 11 7#6 12 7#7 10 6#8 7 5#9 2 3pd.cutbins = [0,2,4,5,6,8,10,12] # Right edgeslabels= [1,2,3,4,5,6,7]df['Cut'] = pd.cut(df.Month, bins=bins, labels=labels)# If want integer labels# df['Cut'] = pd.cut(df.Month, bins=bins, labels=False)+1 # Month Mapped Cut#0 3 2 2#1 3 2 2#2 7 5 5#3 2 1 1#4 4 2 2#5 11 7 7#6 12 7 7#7 10 6 6#8 7 5 5#9 2 1 1