Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

python - np.where multiple conditions?

I'm using numpy to add to a new column baased off another column. I believe only 2 arguments are allowed but I need 3. Is this possible with an elif statement?

I need S3 to be "VM", CloudWatch to be "Disk", and everything else to go as "Other"

What I have:

data_1 = pd.read_csv('data.csv')

data_1['ADDED_COLUMN1'] = np.where(data_1.DIMENSION.isin(['S3', 'Glacier']), 
'VM', 'Other')

Output:

S3             VM
Glacier        VM
S3             VM
S3             VM
CloudWatch     VM
Athena       Other

What I want:

S3             VM
Glacier        VM
S3             VM
S3             VM
CloudWatch     Disk
Athena         Other

How do I add 1 more argument to get this output?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use numpy.select here

conditions  = [ data_1.DIMENSION.isin(["s3","Glacier"]), data_1.DIMENSION == "CloudWatch" ]
choices = ["VM", "Disk"]

data_1["ADDED_COLUMN1"] = np.select(conditions, choices, default="Other")

data_1
    DIMENSION ADDED_COLUMN1
0          s3            VM
1     Glacier            VM
2          s3            VM
3          s3            VM
4  CloudWatch          Disk
5      Athena         Other


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...