熊猫:选择范围在

时间:2019-09-19 09:28:51

标签: python pandas dataframe

我有一个数据框,我想从该数据框中选择一个范围内的数据,只有该范围的第一次出现。

数据框:

data = {'x':[1,2,3,4,5,6,7,6.5,5.5,4.5,3.5,2.5,1], 'y':[1,4,3,3,52,3,74,64,15,41,31,12,11]} 
df = pd.DataFrame(data) 

例如:从2到6中选择x,第一次出现

     x   y
0   1.0  1 #out of range
1   2.0  4 #out of range
2   3.0  3 #this first occurrence
3   4.0  3 #this first occurrence
4   5.0  52 #thisfirst occurrence
5   6.0  3  #out of range
6   7.0  74 #out of range
7   6.5  64 #out of range
8   5.5  15 #not this since repeating RANGE
9   4.5  41 #not this since repeating RANGE
10  3.5  31 #not this since repeating RANGE
11  2.5  12 #not this since repeating RANGE
12  1.0  11 #out of range

输出

     x   y
2   3.0  3 #this first occurrence
3   4.0  3 #this first occurrence
4   5.0  52 #thisfirst occurrence

我正在尝试修改以下示例:Select DataFrame rows between two dates以便在2个值之间首次出现时选择数据:

xlim=[2,6]
mask = (df['x'] > xlim[0]) & (df['x'] <= xlim[1])
df=df.loc[mask] #need to make it the first occurrence here

1 个答案:

答案 0 :(得分:3)

这是一种方法:

# mask with True whenever a value is within the range
m = df.x.between(2,6, inclusive=False)
# logical XOR with the next row and cumsum
# Keeping only 1s will result in the dataframe of interest
df.loc[(m ^ m.shift()).cumsum().eq(1)]

    x   y
2  3.0   3
3  4.0   3
4  5.0  52

详细信息-

df.assign(in_range=m, is_next_different=(m ^ m.shift()).cumsum())

     x    y   in_range  is_next_different
0   1.0   1     False                  0
1   2.0   4     False                  0
2   3.0   3      True                  1
3   4.0   3      True                  1
4   5.0  52      True                  1
5   6.0   3     False                  2
6   7.0  74     False                  2
7   6.5  64     False                  2
8   5.5  15      True                  3
9   4.5  41      True                  3
10  3.5  31      True                  3
11  2.5  12      True                  3
12  1.0  11     False                  4