简体   繁体   中英

Pandas dataframe conditional column update

Here is my dataframe:

                ACC  Count  SumOneLotPNL  MinAVG  U   PerLotPNL   Y
AS                                                                 
30106EURTRY1  30106      1         34.84     5.0  A   34.840000   3
30106USDTRY0  30106     16      -3018.18  8190.0  T -261.623333   2
30106USDTRY1  30106      6       1804.28  2069.0  A  248.820000   6
30106WTIOIL0  30106     43      -8410.00  1160.0  T -331.410000  23
30106WTIOIL1  30106     80       6600.00  1045.8  A   80.124000  37

If value of column U is T, I want to multiply the value of column Y with -1 in the same row. How can I do that?

Thanks,

Make use of .loc after selecting the subset where the condition is satisfied and then incrementally multiply the corresponding rows in Y with -1 to see the effect:

df.loc[df['U'] == 'T', 'Y'] *= -1
df

在此输入图像描述

Note: The notation *= multiplies the variable and a value, thereby making the outcome the variable.

creative solution

#       |<- -1 if 'T' else 1  ->|
df.Y *= df.U.ne('T').mul(2).sub(1)
df

                ACC  Count  SumOneLotPNL  MinAVG  U   PerLotPNL   Y
AS                                                                 
30106EURTRY1  30106      1         34.84     5.0  A   34.840000   3
30106USDTRY0  30106     16      -3018.18  8190.0  T -261.623333  -2
30106USDTRY1  30106      6       1804.28  2069.0  A  248.820000   6
30106WTIOIL0  30106     43      -8410.00  1160.0  T -331.410000 -23
30106WTIOIL1  30106     80       6600.00  1045.8  A   80.124000  37

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