How to create a new column basis on calculative condtions?

Viewed 36

There are two column A and column Aging. Required to create a new column called simulator with condition (mean+std) of column A. For example for all Aging==2, simulator should be calculated basis the corresponding values in column A .

I tried the the given below code however when i change the Aging value, the simulator value does not change. Provided below is the reference data and the code i tried.

# seed the pseudorandom number generator
from numpy.random import seed
from numpy.random import randint
# seed random number generator
seed(1)
# generate some random numbers
x=pd.DataFrame(randint(0, 10, 20),columns=list('A'))
# reset the seed
seed(1)
# generate some random numbers
x['aging']=pd.DataFrame(randint(1,5,20),columns=list('z'))

x['simulator']=np.where(x['aging']==2,x.A.mean()+x.A.std(),0)
x['simulator']=np.where(x['aging']==4,x.A.mean()+x.A.std(),x['simulator'])
1 Answers

np.where evaluates your values first and then chooses those values based on the condition. So in both cases x.A.mean() + x.A.std() is calculated over the entire DataFrame, and being the same DataFrame in each case, the chosen value is the same.

The only difference is that the value is only set to the rows where x['aging']==2 or x['aging']==4, depending upon the condition.

If you want the column to be the mean + std within each aging, use groupby + transform:

gp = x.groupby('aging')['A']
x['simulator'] = gp.transform('mean') + gp.transform('std')

    A  aging  simulator
0   5      2   7.088436
1   8      4   6.835113
2   9      1   9.041928
3   5      1   9.041928
4   0      4   6.835113
5   0      2   7.088436
6   1      4   6.835113
7   7      2   7.088436
8   6      4   6.835113
9   9      1   9.041928
10  2      1   9.041928
11  4      2   7.088436
12  5      1   9.041928
13  2      4   6.835113
14  4      2   7.088436
15  2      1   9.041928
16  4      3   7.621320
17  7      2   7.088436
18  7      3   7.621320
19  9      1   9.041928
Related