Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:选择范围之间数据帧行的首次出现_Python_Pandas_Dataframe - Fatal编程技术网

Python 熊猫:选择范围之间数据帧行的首次出现

Python 熊猫:选择范围之间数据帧行的首次出现,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据帧,我想从中选择一个范围内的数据,只有这个范围的第一个出现 数据帧: 数据={'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.DataFramedata 例如:从2到6中选择x,第一次出现: xy 0 1.0 1超出范围 1 2.0 4超出范围 2 3.0 3这是第一次发生 3 4.0 3这是第一次发生 4.5.0 52首次出现 5 6.0 3超出范围 6

我有一个数据帧,我想从中选择一个范围内的数据,只有这个范围的第一个出现

数据帧:

数据={'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.DataFramedata 例如:从2到6中选择x,第一次出现:

xy 0 1.0 1超出范围 1 2.0 4超出范围 2 3.0 3这是第一次发生 3 4.0 3这是第一次发生 4.5.0 52首次出现 5 6.0 3超出范围 6 7.0 74超出范围 7.6.5 64超出范围 8.5.5 15由于重复的范围,因此不需要这样做 9.4.5 41由于重复范围,因此不在此范围内 10 3.5 31由于重复范围,因此不在此范围内 11.2.5 12由于重复范围,因此不在此范围内 12 1.0 11超出范围 输出

xy 2 3.0 3这是第一次发生 3 4.0 3这是第一次发生 4.5.0 52首次出现 我试图修改此示例:要在两个值之间选择第一次出现的数据:

xlim=[2,6] mask=df['x']>xlim[0]&df['x']这里有一种方法:

# 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

您是指该范围内的第一组连续值?5.5行8如何不是第一次出现?是的,数据是一个来回重复的测量值。我只需要第一次向前迭代,第一次向前出现范围内的值,因为我们已经到了6,5.5是向后的,所以它是向外的。谢谢,你能详细说明一下它在做什么吗?是的,在@david8中添加一些解释,所以每次in_范围更改真/假时,不同的部分都会赋值+1?是的,所以m^m.shift会在每次有0^1或1^0时产生一个真,与true和false相同,因此每当从1更改为0或反之亦然。这将在第一组连续值中发生一次,第一个值在该范围内。通过将累积和设置为1,第一组中的所有值都将被设置为1。然后只要在1所在的地方建立索引@David8就行了