Python/Pandas - How to remove extra space between two words from a data frame column

Asked

Viewed 1,686 times

0

The "strip" function removes the spaces on the left and right, but does not remove the spaces between the words:

raw_data = {'NAME': ['   José  Luiz   da   Silva   ']}
df = pd.DataFrame(raw_data, columns = ['NAME'])
df['NAME'] = df['NAME'].str.strip()

1 answer

2

import pandas as pd
rdata = {'NAME': ['   José           Luiz   da       Silva   ']}
df = pd.DataFrame(rdata, columns = ['NAME'])

for i, row in df.iterrows():
  df.set_value(i,'NAME',' '.join(row.NAME.split()))

print (df)  

Output:

                 NAME
0  José Luiz da Silva

Run on repl.it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.