Pandas DF: Formatting Hyphenated Last Names

Viewed 73

I'm building a python module to help me format text for work. I work with application and survey data that I'm importing into our company's CRM so I'm trying to turn something like " louis-dreyfus " into "Louis-Dreyfus" where the name is capitalized in the beginning and after the hyphen. My code worked when I wrote out the function in the same jupyter notebook that I imported the dataset into but when I write out the function in a module and import it, " louis-dreyfus " turns into "Louis-dreyfus". Here's my code so far:

def format_names(df_name, col_name):
    for idx, val in enumerate(df_name[col_name]):
        val = val.strip()
        if '-' in val:
            split = val.split('-')
            n1 = split[0].strip()
            n2 = split[1].strip()
            n1 = n1.capitalize()
            n2 = n2.capitalize()
            hyphen_names = n1 + '-' + n2 
            df_name[col_name].iloc[idx] = hyphen_names

If I print out df_name[col_name].iloc[idx] at the end of the "if" statement I get the correct output "Louis-Dreyfus" but it doesn't seem to replace the value in the dataframe. HELP!

2 Answers

You can try this:

Sample data:

import pandas as pd
df = pd.DataFrame({'names':[" louis-dreyfus ", "some-name    ", "    another-more-complex-name   "]})

Code:

def format_names(s):
    return '-'.join([x.strip().capitalize() for x in s.split('-')])

df['names'].map(format_names)

Result:

# Out[10]: 
# 0                Louis-Dreyfus
# 1                    Some-Name
# 2    Another-More-Complex-Name
# Name: names, dtype: object

Don't know about the efficiency but perhaps try

import pandas as pd
from io import StringIO

data = '''\
id,name
101,asdf-qwer
102,justin
103,foo-bar
104,bar-foo
105,was here
'''

f = StringIO(data)
df = pd.read_csv(f)

print(df)

df['name'] = df['name'].str.title()

print(df)
Related