将每个值分配给dataFram上的一个范围

2024-10-05 13:26:29 发布

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

我有一个这样的数组states

[(1,3), (3,5), (5,7), (7,9)]

和这样的一个数据帧df

^{pr2}$

我需要在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)

但我需要一种更快更有效的方法来处理更大的数据帧,有什么想法吗?在


Tags: and数据indfforindexreturnif
2条回答

使用pandas.cut()

bins=pd.Series([1,3,5,7,9, np.inf])   
df['state'] = pd.cut(df.y, bins=bins, labels=bins.index[:-1], include_lowest=True)

输出:

^{pr2}$

如何将states元组列表转换为平面pd.Series

In [125]: states
Out[125]: [(1, 3), (3, 5), (5, 7), (7, 9)]

In [126]: bins = pd.Series(np.unique(list(sum(states, ()))))

In [127]: bins
Out[127]:
0    1
1    3
2    5
3    7
4    9
dtype: int32

In [128]: bins.tolist()
Out[128]: [1, 3, 5, 7, 9]

要避免使用.apply()遍历所有行,而是以矢量化的方式分配states,请执行以下操作:

df['states'] = 0
for i, state in enumerate(states):
    df.loc[(df.y > state[0]) & (df.y <= state[1]), 'states'] = i

获得:

^{pr2}$

相关问题 更多 >

    热门问题