Pandas isin()函数用于连续间隔

时间:2015-06-03 15:34:27

标签: python pandas

让我们说我想构建一个虚拟变量,如果一个数字介于1和10之间,则该变量为真,我可以这样做:

df['numdum'] = df['number'].isin(range(1,11))

连续间隔有没有办法做到这一点?因此,创建一个虚拟变量,如果数字在一个范围内,则为true,允许非整数。

3 个答案:

答案 0 :(得分:4)

Series个对象(包括数据框列)使用between方法:

>>> s = pd.Series(np.linspace(0, 20, 8))
>>> s
0     0.000000
1     2.857143
2     5.714286
3     8.571429
4    11.428571
5    14.285714
6    17.142857
7    20.000000
dtype: float64
>>> s.between(1, 14.5)
0    False
1     True
2     True
3     True
4     True
5     True
6    False
7    False
dtype: bool

答案 1 :(得分:1)

这有效:

df['numdum'] = (df.number >= 1) & (df.number <= 10)

答案 2 :(得分:1)

你也可以用cut()做同样的事情。如果只有两个类别,则没有真正的优势:

>>> df['numdum'] = pd.cut( df['number'], [-99,10,99], labels=[1,0] )

   number numdum
0       8      1
1       9      1
2      10      1
3      11      0
4      12      0
5      13      0
6      14      0

但如果您有多个类别,那就太好了:

>>> df['numdum'] = pd.cut( df['number'], [-99,8,10,99], labels=[1,2,3] )

   number numdum
0       8      1
1       9      2
2      10      2
3      11      3
4      12      3
5      13      3
6      14      3

标签可以是TrueFalse(如果是首选标签),或者您根本无法指定标签,在这种情况下标签将包含截止点的信息。