Home > Software design >  python to check the value of every row in a dataframe
python to check the value of every row in a dataframe

Time:12-06

I have a column of values in a dataframe as below. I want to create a new column that checks every row of the current column and and a value of 0 if it is larger than -5 or return -5 if the value is smaller than -5. Is there a quick way to do this? Thanks

input :

    value 
0   -2.26
1   -5.70
2   -2.14
3   -2.30
4   -2.22
5   -4.86
6   -5.07
7   -3.86
8   -3.26

output :

    value   new_value
0   -2.26           0
1   -5.70          -5
2   -2.14           0
3   -2.30           0
4   -2.22           0
5   -4.86           0
6   -5.07          -5
7   -3.86           0
8   -3.26           0

CodePudding user response:

You can use np.where

df['new_values'] = np.where(df['values'] < -5, -5, 0)

CodePudding user response:

It is also possible to achieve it with a combination of map and lambda.

import pandas as pd
import numpy as np

df = pd.DataFrame({'value': np.random.normal(-5, 1, 10)})
df ['new_value'] = df['value'].map(lambda x: -5 if x < -5 else 0)
  • Related