Home > database >  split a cell in pandas DF, and call the element in the return list
split a cell in pandas DF, and call the element in the return list

Time:08-24

i've got a excel fill with a column named 'Correspondant', with for each row, for example "Mr Michel DURAND", so I split it with:

df['Correspondant Split']=df['Correspondant'].str.split(' ')

but now I can't use:

df_modele_contacts['Nom du contact *']=df['Correspondant Split'][-1]
df_modele_contacts['Pr?nom du contact']=df['Correspondant Split'][1]

have you an idea? how can I accede to the list I created?

CodePudding user response:

Using your logic : (you forgot to give the row index)

test = {'Correspondant':"Mr Michel DURAND"}

df_modele_contacts = pd.DataFrame(test, index=[0])
df_modele_contacts['Correspondant Split']=df['Correspondant'].str.split(' ')

df_modele_contacts['Nom du contact *']=df['Correspondant Split'][0][2]
df_modele_contacts['Pr?nom du contact']=df['Correspondant Split'][0][1]

I would recommend doing something like this instead :


df_modele_contacts = pd.DataFrame(test, index=[0])

df_modele_contacts['Nom du contact'] = [x.split()[2] for x in df['Correspondant']]
df_modele_contacts['prenom du contact'] = [x.split()[1] for x in df['Correspondant']]

df_modele_contacts

CodePudding user response:

thank you!! yes it seams better, but, wy does it return: AttributeError: 'float' object has no attribute 'split'

in this column, it is only string... or empty cell.

  • Related