简体   繁体   中英

Creating a new column based on three existing columns

I have a data frame with three columns, target_degrees , low_degrees , and high_degrees . I would like to make a new column labeled success that checks to see if target_degrees is located between low_degrees and high_degrees .

example dataframe:

target_degrees   low_degrees   high_degrees   success
   10                0              50          1
   50                45             100         1
   20               100             200         0
   1                300             350         0

I have tried using np.where in the following code but I am getting a syntax error.

df['success'] = np.where(df['target_degrees'] is in np.arange(df['low_degrees'], df['high_degrees']), 1, 0)

Use multiple conditions:

df['success'] = np.where(((df['target_degrees'] >= df['low_degrees']) & (df['target_degrees']<= df['high_degrees'])), 1, 0)

output :

  target_degrees  low_degrees   high_degrees    success
0       10                 0         50            1
1       50                45        100            1
2       20               100        200            0
3        1               300        350            0

between方法更简洁一点:

df['success'] = df['target_degrees'].between(df['low_degrees'], df['high_degrees'])

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