Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: get all positive delta values efficiently

Tags:

python

pandas

I am looking for an efficient way to turn this pandas dataframe:

   A  B  C
0  0  1  0
1  0  1  1
2  1  1  1
3  1  1  0
4  0  0  1

into

   A  B  C
0  0  1  0
1  0  0  1
2  1  0  0
3  0  0  0
4  0  0  1

I only want "1" in a cell, if in the original dataframe the value jumps from "0" to "1". If it's the first row, I want a "1", if "1" is the start value. I have to use this operation often in my project and on a large dataframe, so it should be as efficient as possible. Thanks in advance!

like image 777
Simon1994 Avatar asked Jan 23 '26 23:01

Simon1994


1 Answers

You can use:

df.diff().clip(0).fillna(df)

output:

   A  B  C
0  0  1  0
1  0  0  1
2  1  0  0
3  0  0  0
4  0  0  1
like image 54
mozway Avatar answered Jan 26 '26 13:01

mozway