简体   繁体   中英

Multiple condition in pandas dataframe - np.where

I have the following dataframe

Year          M  
1991-1990     10
1992-1993      9

What I am trying to so is a if statement: =IF(M>9,LEFT(Year),RIGHT(C2,4))*1

So basically if M if 10 choose the left value of the column year else choose the second value

I tried using np.where but I have no idea how to choose between two values in the same column.

Help?

You can do this:

In [448]:  df['val'] = np.where( df['M'].gt(9),\ 
     ...:                       df.Year.str.split('-').tolist()[0],\ 
     ...:                       df.Year.str.split('-').tolist()[1] )                                                                                                                                         


In [444]: df                                                                                                                                                                                                
Out[444]: 
        Year   M   val
0  1991-1990  10  1991
1  1992-1993   9  1993

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