Replace certain value in pandas Dataframe without knowing neither column nor row
Very simple using mask
:
df.mask(df>110,'OVER').mask(df<90,'UNDER')
Result:
P1899 P3486 P4074 P3352 P3500 P3447
Time
1997 100 UNDER UNDER UNDER OVER UNDER
1998 100 101.598 UNDER UNDER 106.032 95.2638
1999 100 97.2346 91.2626 UNDER 104.539 95.86
2000 100 100.76 UNDER UNDER 103.74 90.2723
2001 100 96.8735 UNDER UNDER 106.371 91.8075
2002 100 95 90.3136 UNDER 109.28 94.4444
Here's a way to do it in a vectorized manner. Do all the strings operations in a separate data frame, and then assign the relevant values in one go:
new_df = df.copy()
new_df.loc[:, :] = " "
new_df[df > 110] = "over"
new_df[df < 90] = "under"
df[(df < 90) | (df > 110)] = new_df
The result:
P1899 P3486 P4074 P3352 P3500 P3447
Time
1997 100.0 under under under over under
1998 100.0 101.598 under under 106.032 95.2638
1999 100.0 97.2346 91.2626 under 104.539 95.86
2000 100.0 100.76 under under 103.74 90.2723
2001 100.0 96.8735 under under 106.371 91.8075
2002 100.0 95 90.3136 under 109.28 94.4444