Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I want to update a column (Names) as follows:

  • if the last character of a word in Names ends with a and is not pizza, then assign c;
  • if the last character of a word in Names ends with o or I or it is pizza, then assign m.

The column to check is

I am trying to change the column name based on the following:

   If the column name ends with a letter 'a' then it should be replaced with pizza then it should not chance else it be assigned with letter 'c'

  If the column name ends with a letter 'o' or 'I' or it is a pizza then it should not chance else it be assigned with the letter 'm'

Names

choriocarcinoma

medulloblastoma

phenylketonuria

counterguerilla

lymphogranuloma

archipelago

braggadocio

chiaroscuro

decrescendo

violoncello

accelerando

afficionado

tachyarrhythmia

teratocarcinoma

caudillismo

cinquecento

countermemo

oligodendroglia

pleuropneumonia

pizza

To get the last character I used the below code:

df['Names'] = [x.strip()[-1] for x in df['Names']]

Checking and assigning new values I did:

if df['Names'] == 'a': 

   df['Names'] = 'c'

elif df['Names'] in ('o','i','pizza'):

   df['Names'] = 'm'

else: 

   df['Names'] = 'Other'

This is also not working

def applyFunc(s):

    if s == 'a' and s != 'pizza':

        return 'c'

    elif s in ('o','i', 'pizza'):

        return 'm'

    return 'other'

Even this didn't work

can anyone help me solve the error?

1 Answer

0 votes
by (36.8k points)

Booleanselect by combines str.endswith(), ampersand, and |for alternative selections. Use nested np.where. Caution; np.select isthe better option

import numpy as np

a= (df.Names.str.endswith('a'))&(df.Names!='pizza')

b= (df.Names.str.endswith('o'))|(df.Names.str.endswith('i'))|(df.Names=='pizza')

df['N']=np.where(a, 'c', np.where(b,'m',df.Names))

 Learn Python for Data Science Course to improve your technical knowledge.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...