Gaurav Bansal
Gaurav Bansal

Reputation: 5660

Subtracting min value from previous value in pandas DataFrame

I want to subtract the minimum value of a column in a DataFrame from the value just above it. In R I would do this:

df <- data.frame(a=1:5, b=c(5,6,7,4,9))
df
  a b
1 1 5
2 2 6
3 3 7
4 4 4
5 5 9
df$b[which.min(df$b)-1] - df$b[which.min(df$b)]
[1] 3

How can I do the same thing in pandas? More generally, how can I extract the row number in a pandas DataFrame where a certain condition is met?

Upvotes: 0

Views: 302

Answers (1)

akuiper
akuiper

Reputation: 214957

You can use argmin to find out the index of the minimum value(the first one if there are ties), then you can do the subtraction based on the location:

index = df.b.argmin()
df.b[index-1] - df.b[index]
# 3

In case the index is not consecutive numbers:

i_index = df.b.values.argmin()
df.b.iat[i_index-1] - df.b.iat[i_index]
# 3

Or less efficiently:

-df.b.diff()[df.b.argmin()]
# 3.0

Upvotes: 2

Related Questions