serah
serah

Reputation: 1

How do I conduct an if condition using pandas

          hours
0          12
1          19
2          22
3          12
4           8
5          24
6          19
7          22 
8          4
9          26

the above is my data, and i have created my DataFrame df as well. Im trying to create a condition where if the values are >= 24 they should essentially print 0, if not to print the value as it is. ive tried df.loc but it doesnt seem to work, it just prints the values again as it is ignoring the condition.

Upvotes: 0

Views: 3098

Answers (2)

hpchavaz
hpchavaz

Reputation: 1388

Mask the hours columns:

df['hours'][df['hours']>=24] = 0

Upvotes: 1

TheFaultInOurStars
TheFaultInOurStars

Reputation: 3608

You can use np.where:

df["hours"] = np.where(df["hours"] >= 24, 0, df["hours"])
df

Output

hours
0 12
1 19
2 22
3 12
4 8
5 16
6 0
7 20
8 4
9 0

Upvotes: 1

Related Questions