So first time posting here and my problem is I need to change middle name to middle initial if there is middle name in full name field using python pandas.
for example)
Keys, Alicia ------> Keys, Alicia
Keys, Alicia T ----->Keys, Alicia T
Keys, Alicia Mary -----> Keys, Alicia M
Pitt, John Paul -----> Pitt, John P
Pitt, John Paul John --> Pitt, Jon Paul J
So if there is no middle name then keep the full name values, if there is a middle initial then keep the middle initial if there is a middle name then change middle name to middle initial.
I've been playing with string split but I do not have a good way to know how to tackle all the cases.
Any help are appreciated. Thank you!!
CodePudding user response:
Judging strictly by the provided example, you could use the following piece of code, which replaces the last word with its first letter, to transform every string:
def transform(name):
words = name.split()
if len(words) < 3:
return name
words[-1] = words[-1][0]
return " ".join(words)
Of course, if the middle name is not the last word of the string, you'd have to find the middle name somehow and use its index instead of -1
.
CodePudding user response:
You could do something like this:
# Get the first letter of the last name
def letterofname(name):
# Separate each word into a list
words = name.split(' ')
# Get the last char
last_name = words[len(words) - 1]
last_char = last_name[len(list(last_name)) - 1]
return last_char
CodePudding user response:
Take a regular expression to substitute those last names with their initials. No complex logic there, just a one-liner :) I made an example regex and substitution for you: