1

i want to give if condition in my pandas column, but nothing applied. I had check dtypes of column and it said Float32, am i wrong in any typing or somewhat i dont know

i had tried this code :

How to use numpy.where with logical operators

Numpy "where" with multiple conditions

multiple if else conditions in pandas dataframe and derive multiple columns

and i try to use numpy.where, but nothing happen.. data['growth'] always have result 2

my code :

data['growth'] = np.where(np.logical_and(data['tqty'] < 0, data['qty_x'] < 0), 1, 2)

i dont prefer to use if or numpy.where

many thanks

hartono -
  • 41
  • 6
  • 2
    can you post the sample data and expected output. may be your data doesn't contain rows that satisfies the two conditions – deadshot Sep 09 '20 at 03:29

1 Answers1

2

Try to use DataFrame's method 'apply':

Using this sample data:

df = pd.DataFrame(data=[(-1, -1), 
                        (-1, 0),
                        (0, -1),
                        (0, 0),
                        (1, 1)],
                  columns=['tqty', 'qtyx'])



|    |   tqty |   qtyx |
|---:|-------:|-------:|
|  0 |     -1 |     -1 |
|  1 |     -1 |      0 |
|  2 |      0 |     -1 |
|  3 |      0 |      0 |
|  4 |      1 |      1 |

You can get this using lambda functions:

df['growth'] = df.apply(
    lambda row: 1 if ((row['tqty'] < 0) & (row['qtyx'] < 0))
    else 2, 
    axis=1)

|    |   tqty |   qtyx |   growth |
|---:|-------:|-------:|---------:|
|  0 |     -1 |     -1 |        1 |
|  1 |     -1 |      0 |        2 |
|  2 |      0 |     -1 |        2 |
|  3 |      0 |      0 |        2 |
|  4 |      1 |      1 |        2 |

'Axis=1' allows you to iterate through rows, and lambda operates over each row testing both conditions.

Augusto Sisa
  • 548
  • 4
  • 15