Reputation: 105
I am trying to create a new column where the value will be the minimum value of all previous rows from existing columns.
For example: Here is my data frame:
A nbr
0 AA 4
1 AB 5
2 AC 2
3 AD 5
4 AE 3
5 AF 6
6 AG 1
7 AH 4
I am trying to add a new column 'nbr_min' using the column nbr.
So the first row for nbr_min will be 4, since this is he first row and the minimum of 4 is 4.
Second row will be the minimum of 4 and 5, which is 4.
Third row will be the minimum of 4,5,and 2, which is 2.
And so on...
The final result should look like this.
I am having hard time doing this in python (with pandas). Any help will be appreciated. I am very close to conclude that this can not be done with python. So solution in any other way is also welcome.
.
Upvotes: 0
Views: 636
Reputation: 75150
Use series.cummin()
:
df['nbr_min']=df.nbr.expanding().min()
Or:
df['nbr_min']=df.nbr.cummin()
print(df)
A nbr nbr_min
0 AA 4 4
1 AB 5 4
2 AC 2 2
3 AD 5 2
4 AE 3 2
5 AF 6 2
6 AG 1 1
7 AH 4 1
Upvotes: 1