Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Data Science by (17.6k points)

I have a DataFrame df:

    A    B

a   2    2 

b   3    1

c   1    3

I want to create a new column based on the following criteria:

if row A == B: 0

if row A > B: 1

if row A < B: -1

so given the above table, it should be:

    A    B    C

a   2    2    0

b   3    1    1

c   1    3   -1 

For typical if else cases I do np.where(df.A > df.B, 1, -1), does pandas provide a special syntax for solving my problem with one step (without the necessity of creating 3 new columns and then combining the result)?

1 Answer

0 votes
by (41.4k points)

1.Firstly, create a function that operates on the rows of your dataframe.

2.After that, apply it to your dataframe passing in the axis=1.

def f(row):

    if row['A'] == row['B']:

        val = 0

    elif row['A'] > row['B']:

        val = 1

    else:

        val = -1

    return val

--------

In [1]: df['C'] = df.apply(f, axis=1)

In [2]: df

Out[2]:

   A  B  C

a  2  2  0

b  3  1  1

c  1  3 -1

Browse Categories

...