我有一个这样的数组states
[(1,3), (3,5), (5,7), (7,9)]
和这样的一个数据帧df
我需要在states
上分配归属范围的索引,以获得如下结果
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
值必须属于范围{
到目前为止我有这个
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)
但我需要一种更快更有效的方法来处理更大的数据帧,有什么想法吗?在
使用pandas.cut():
输出:
^{pr2}$如何将
states
元组列表转换为平面pd.Series
:要避免使用
.apply()
遍历所有行,而是以矢量化的方式分配states
,请执行以下操作:获得:
^{pr2}$相关问题 更多 >
编程相关推荐