简体   繁体   中英

Cutting every nth row in dataframe in Python

I have a dataframe with columns like so:

x   y   z
1   10  20
2   10  18
3   11  16.5
4   11  12
5   12  23
6   11  21
7   10  19
8   10  26
.
.

Every time z_n+1 is greater than z_n I want to cut that z_n.

The output would be:

x   y   z
1   10  20
2   10  18
3   11  16.5
5   12  23
6   11  21
8   10  26
.
.

It doesn't occur every x-many times - the index of each change from smaller to larger z_n is not 'regular'.

Is there an easy way to do this?

We can use shift to look one row back and take the reverse with ~ :

df[~(df['z'].shift() < df['z'])]

   x   y     z
0  1  10  20.0
1  2  10  18.0
2  3  11  16.5
3  4  11  12.0
5  6  11  21.0
6  7  10  19.0

Try:

df[~(df.z.diff(-1) < 0)]

Output:

   x   y     z
0  1  10  20.0
1  2  10  18.0
2  3  11  16.5
4  5  12  23.0
5  6  11  21.0
7  8  10  26.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM