我有這樣每個值分配給一個範圍上數據幀
[(1,3), (3,5), (5,7), (7,9)]
陣列states
和這樣
l y
0 a 8
1 b 3
2 c 7
3 d 4
4 e 1
我需要分配屬於範圍的索引上states
一個數據幀df
得到像這樣的東西
l y state
0 a 8 3
1 b 3 0
2 c 7 2
3 d 4 1
4 e 1 0
對於每個範圍在states
,該y
值必須屬於範圍(start, end]
除了在第一範圍,其中1
不屬於(1,3)
到目前爲止,我有這個
def asign(x):
for a,b in states:
if x>=a and x<=b:
return states.index((a,b))
df['state'] = df.y.apply(asign)
,但我需要一個更快,更有效的方法更大的數據框架,任何想法?