Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove second character in a string in DataFrame

I have a DataFrame with a column of names that include the middle initial. I need to remove the middle initial which is the second character in the string.

df = pd.DataFrame({'alpha': ['1', '2', '3'],
                   'beta': ['JRLeparoux', 'BJHernandez,Jr.','SXBridgmohan'],})

Here is what I tried:

def fixbadname(word):
    filelist2= [] 
    filelist = []
    for elem in word:
        filelist.append(elem)
         for file in filelist:
            file = file.replace(file[1],"") 
            filelist2.append(file)

    return filelist2

df['beta'].apply(fixbadname)

This is the desired output:

df = pd.DataFrame({'alpha': ['1', '2', '3'],
                   'beta': ['JLeparoux', 'BHernandez,Jr.','SBridgmohan'],})
like image 907
Erich Avatar asked Sep 01 '26 12:09

Erich


1 Answers

df.beta = df.beta.str[0:1] + df.beta.str[2:];
That should work.
If you want some explanations; ask me.

like image 92
DasFranck Avatar answered Sep 03 '26 02:09

DasFranck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!