Home > Software engineering >  If the value is a number between x and y, change it to z (pd df)
If the value is a number between x and y, change it to z (pd df)

Time:08-04

data.loc[data.cig_years (10 < a < 20), 'cig_years'] = 1

This is the code I have tried, but it's not working. In pseudocode I want:

In the df 'data'
In the column 'cig_years'
If the value is a number between 10 and 20, change it to 1 

Is there a pythonic way of doing this? Preferably without for loops.

CodePudding user response:

you need to use your dataframe name "data" and change it using .loc like below:

data.loc[10 < data['cig_years'] < 20, 'cig_years'] = 1

CodePudding user response:

I got you, you can filter pandas dataframes with square brackets []

data['cig_years'] [ (data['cig_years']>10) | (data['cig_years']<20) ] = 1

this basically says,

the columns 'cig_years' in data, where the columns 'cig_years' is more than 10, or less than, is set equal to 1

this is super useful in pd dataframes cause you can filter for specific columns, or filter by conditions on other columns, then set those filtered values

  • Related