简体   繁体   中英

Greater/less than in if statement

Still looking for an answer, help is very much appreciated!

I am working on a dataset containing different types of data about cars I want to add a value to the horsepower_score column, if the value of the horsepower column is greater than x but less than y.

I want to add the value:

1 if horsepower is less than or equal to 50

2 if horsepower is greater than 50 but less than or equal to 100

3 if horsepower is greater than 100 but less than or equal to 200

4 if horsepower is greater than 200 but less than or equal to 250

5 if horsepower is greater than 250 but less than or equal to 300

I have tried several different codes, but I can't make any of them work.

import pandas as pd
data=[[150,0],[275,0],[30,0],[90,0],[220,0]]
df=pd.DataFrame(data,columns=['horsepower','horsepower_score'])

if df['horsepower']<=50:
    df['horsepower_score']=1

if df['horsepower']>50 & <=100:
    df['horsepower_score']=2

if df['horsepower']>100 & <=200:
    df['horsepower_score']=2

if df['horsepower']>200 & <=250:
    df['horsepower_score']=4

if df['horsepower']>250 & <=300:
    df['horsepower_score']=5

So my desired result would look like this:

horsepower horsepower_score
150 3
275 5
30 1
90 2
220 4

Update: Im still looking for a solution. The only answer that worked partially is the one from @Andreas, but that suggestion keeps on adding the number to the column when the code is run several times, and i simply want to assign the number once.

In python you can chain these conditions, which makes pretty nice to read.

if 100 < df['horsepower'] < 200:
    df['horsepower_score']=3

Or you use the more traditional way:

if df['horsepower'] > 100 & df['horsepower'] < 200:
    df['horsepower_score']=3

You have to break it into two separate comparisons. Those comparisons form a boolean index you can use to slice df .

ix = df['horsepower']>100 & df['horsepower']<200
df.loc[ix, 'horsepower_score'] = 3

You wrote

I want to add a value to horsepower_score

Therefore I assume there are already values in horsepower_score, and you want to add 3 to the existing number. If that is the case, you can use this:

df['horsepower_score'] += (df['horsepower'].ge(100) & df['horsepower'].le(200)) * 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM