set a specific formula for a specific column in panda

Viewed 32

The data frame is like below

df:

A B C D
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

I want to set a specific formula only for column D.

Formula : (each value in [D] - first value of [D])/SD SD = df['D'].std()

I wrote this code and did not work:

    Funtion = (df.D.iloc[] - df.['D'].iat[0])/SD
    df['D'] = df['D'].apply(Function, axis=1)

Is there also a way to use "for" cycle?

1 Answers

Use simple vectorial code, no need for apply (which would be much less efficient):

df['D2'] = df['D'].sub(df['D'].iat[0])/df['D'].std() 

output (as new column D2 for clarity):

    A   B   C   D        D2
0   1   2   3   4  0.000000
1   5   6   7   8  0.774597
2   9  10  11  12  1.549193
3  13  14  15  16  2.323790
Related