2016-06-20 41 views
1

我有这样每个值分配给一个范围上数据帧

[(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) 

,但我需要一个更快,更有效的方法更大的数据框架,任何想法?

回答

0

使用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) 

输出:

In [113]: df 
Out[113]: 
    l y state 
0 a 8  3 
1 b 3  0 
2 c 7  2 
3 d 4  1 
4 e 1  0 

如何在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] 
0

为了避免上循环使用.apply()所有行而是分配states在矢量方式:

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

获得:

l y states 
0 a 8  3 
1 b 3  0 
2 c 7  2 
3 d 4  1 
4 e 1  0 
相关问题