Skip to content
Advertisement

Add a comma after two words in pandas

I have the following texts in a df column:

La Palma
La Palma Nueva
La Palma, Nueva Concepcion
El Estor
El Estor Nuevo
Nuevo Leon
San Jose
La Paz Colombia
Mexico Distrito Federal
El Estor, Nuevo Lugar

What I need is to add a comma at the end of each row but the condition that it is only two words. I found a partial solution:

df['Column3'] = df['Column3'].apply(lambda x: str(x)+',')

(solution found in stackoverflow)

Advertisement

Answer

Given:

                        words
0                    La Palma
1              La Palma Nueva
2  La Palma, Nueva Concepcion
3                    El Estor
4              El Estor Nuevo
5                  Nuevo Leon
6                    San Jose
7             La Paz Colombia
8     Mexico Distrito Federal
9       El Estor, Nuevo Lugar

Doing:

df.words = df.words.apply(lambda x: x+',' if len(x.split(' ')) == 2 else x)
print(df)

Outputs:

                        words
0                   La Palma,
1              La Palma Nueva
2  La Palma, Nueva Concepcion
3                   El Estor,
4              El Estor Nuevo
5                 Nuevo Leon,
6                   San Jose,
7             La Paz Colombia
8     Mexico Distrito Federal
9       El Estor, Nuevo Lugar
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement