hegdep
hegdep

Reputation: 596

Ensure all values in a dataframe column are between two values

Suppose I have a dataframe that looks like this and I want to ensure all values within the column 'T' lie between 129 and 130. i.e. when a value is greater than 130, it should get subtracted until it lies between 129 and 130. Similarly, if the value is less then 129, I want to keep adding 1 til the value lies between 129 and 130.

    T
0   129.3
1   129.1
2   128.9
3   128.9
4   128.9
5   129.6
6   129.4
7   129.2
8   130.1
9   129.8
10  129.7
11  130.4
12  130.7
13  127.9
14  130.4
15  130.0
16  129.0
17  128.5
18  128.7
19  129.5
20  129.9
21  130.1
22  129.6
23  129.3
24  128.7
25  128.6
26  128.8
27  129.3
28  129.6
29  129.2
30  129.1
31  129.0
32  128.7
33  128.6
34  128.8
35  129.1
36  129.5
37  130.0
38  129.4
39  129.3

For some reason, the following code doesn't seem to work:

for i in df['T']: 
    if i<129:
        while i<129:
            i+=1
    if i>130: 
        while i>130:
            i-=1

Upvotes: 1

Views: 111

Answers (1)

Sasha Tsukanov
Sasha Tsukanov

Reputation: 1125

If you wan't the result the same as when you add or subtract values of 1:

import numpy as np
df['T'] = df['T'] % 1 + 129

If you just want to bound the values to be between 129 and 130 please use:

df['T'] = df['T'].clip(129, 130)

Upvotes: 3

Related Questions