Home > OS >  Create a new column based on another column in a dataframe
Create a new column based on another column in a dataframe

Time:12-23

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

CodePudding user response:

 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

CodePudding user response:

Note that there's no need to use apply() or a lambda as in the original question, since comparison of a pandas Series and a string value can be done in a vectorized manner as follows:

df1['ball_faced'] = df1.extra_type.ne('wides').astype(int)

Output:

  extra_type  ball_faced
0        NaN           1
1    legbyes           1
2      wides           0
3       byes           1

Here are links to docs for ne() and astype().

  • Related