Take first part of a string for each row of a dataframe

Viewed 94

I have a dataset like that


        Title                   Location                                            Cuisine 
restaurant_id                                   
0   ['Dove Bistrot Lenovo       Corso Giacomo Matteotti 8/10 Primo Piano Spazi...   Italian, Seafood, Mediterranean, Healthy, Hawa...   
1   ['Mabuhay Restaurant        Bastioni di Porta Volta 9, 20121 Milan Italy        Filipino, Healthy   
2   ['Star Zagros Kebabbar      Corso 22 Marzo, 38, 20135 Milan Italy               Middle Eastern, Turkish, Pub, Bar, Internation...   
3   ['Shabby Grill Restaurant   Via Domokos 4, 20147 Milan Italy                    Italian, Steakhouse, Barbecue   
4   ['Il Panino del Laghetto    Via Laghetto 7, 20122 Milan Italy                   Italian, Street Food, Fast Food

If I type df.info() I get this:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 273 entries, 0 to 272
Data columns (total 9 columns):
 #   Column    Non-Null Count  Dtype 
---  ------    --------------  ----- 
 1   Title     273 non-null    object
 2   Location  273 non-null    object
 3   Cuisine   273 non-null    object

I would like to create a 'Category' column that just keep the first world of the Cuisine column, such as, for the 5 rows listed: Italian, Filipino, Middle Eastern, Italian, Italian

If I do something like this:

df['Category'] = df['Cuisine'].partition(',')

It would say:

AttributeError: 'Series' object has no attribute 'partition'

How do I fix this?

1 Answers

partition method can be accessed from Series.str but you are trying to use it directly on pandas Series by df['Cuisine'].partition(',') and that's the reason why you are getting the error.

Also, you need to take the first item after calling Series.str.partition, thats what [0] is doing in the code below:

df['Category'] = df['Cuisine'].str.partition(',')[0]

                        Title        Location         Cuisine        Category
restaurant_id                                                                
0              ['Dove Bist...  Corso Giaco...  Italian, Se...         Italian
1              ['Mabuhay R...  Bastioni di...  Filipino, H...        Filipino
2              ['Star Zagr...  Corso 22 Ma...  Middle East...  Middle Eastern
3              ['Shabby Gr...  Via Domokos...  Italian, St...         Italian
4              ['Il Panino...  Via Laghett...  Italian, St...         Italian

But better option would be just to use Series.str.split with maxsplit parameter n=1:

df['Category']=df['Cuisine'].str.split(',', n=1).str[0]
Related