首页 > 解决方案 > Pandas Max or Min Row value in a new column based on value another colum

问题描述

So there are 3 columns in the pandas dataframe

I want to create 4th column D, which would based on a condition that if A > 5 then D would have a value of B else value of C. This is for each row

A,B,C    
1,1,2
6,2,3
7,3,1

For example, if you see for the new column D

D row1 = 1 # because A < 5, row of B would be chosen

D row2 = 3 # because A > 5, row of C would be chosen

D row3 = 1 # because A > 5, row of C would be chosen

So the final dataframe would be like

A,B,C,D    
1,1,2,1
6,2,3,3
7,3,1,1

标签: pythonpandas

解决方案


I think you can use

import numpy as np
df['D'] = np.where(df['A']>5, df['C'], df['B'])

推荐阅读