Search code examples
pandaslambdaapply

Create a new column based on another column in a dataframe


I have a df with multiple columns. One of my column is extra_type. Now i want to create a new column based on the values of extra_type column. For example

extra_type
NaN
legbyes
wides
byes

Now i want to create a new column with 1 and 0 if extra_type is not equal to wide then 1 else 0 I tried like this

df1['ball_faced'] = df1[df1['extra_type'].apply(lambda x: 1 if [df1['extra_type']!= 'wides'] else 0)]

It not working this way.Any help on how to make this work is appreciated expected output is like below

extra_type  ball_faced
NaN           1
legbyes       1
wides         0
byes          1

Solution

  •  df['ball_faced'] = df.extra_type.apply(lambda x: x != 'wides').astype(int)
    
    extra_type ball_faced
    0 NaN 1
    1 legbyes 1
    2 wides 0
    3 byes 1