简体   繁体   中英

Create new column with conditional operations on existing columns

I'm extracting data within certain ranges and coming up with new columns that represent 1 when the values in a column fall within that range and 0 when they don't.

I tried using boolean conditions with no luck.

data["normal"]=np.where((data["sysBP"]<80) & (data["diaBP"]<120),1,0)

data["prehyper"]=np.where(((data["sysBP"]<90) & (data["sysBP"]>=80)) & 
                          ((data["diaBP"]<140) & (data["diaBP"]>=120)),1,0)

I expect the new column show 1 for that data that lies within the range and 0 for those that don't. I got a column with all 0s with my above code.

You can use the astype(int) to convert True to 1 and False to 0:

data["normal"] = ((data["sysBP"]<80) & (data["diaBP"]<120)).astype(int)

data["prehyper"] = ((data["sysBP"]<90) & (data["sysBP"]>=80) & (data["diaBP"]<140) & (data["diaBP"]>=120)).astype(int)

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