How to add an ordinal data column based on prices to dataframe?

118 Views Asked by At

I have a dataset of used cars, there is a column of prices in the dataset. I want to introduce a new ordinal column with the values (high, medium, and low) considering the prices of cars like so:

price ordinal
higher than 20,000 high
10,000-20,000 medium
below 10,000 low

Dataset: screenshot of dataset

2

There are 2 best solutions below

0
On

You can try with cut

df['ordinal'] = pd.cut(df['price'],
                       [0,10000,20000,np.Inf],
                       labels = ['Low','Medium','High'])
 
0
On
df["ordinal"] = df["price"].apply(lambda x: "high" if x > 20000 else "low" if x < 10000 else "medium")

what is apply? apply is a method that apply it's first paramater (lambda) on all rows (or something else depends on second parameter).

but, there, and what is our function (lambda):

it just has one parameter (x) and check one if-else, we can rewite it again:

if x > 20000:
    return "high"
else:
    if x < 10000:
        return "low"
    else:
        return "medium"

we refer to this type of if-else as ternary statement or one-line-if-else

what-must-do-if-statement-is-true if statement else what-must-do-if-statement-is-false

and you can define another ternary in what-must-do-if-statement-is-false part like above,

and in what-must-do-if-statement-is-true part, using parentheses: (another-ternary) if statement else what-must-do-if-statement-is-false