Example of how to create initials from a full name dataframe column with pandas and python:
Create a dataframe with pandas
Let's first create a data with pandas with a column with full names:
import pandas as pdimport numpy as npdata = {'Full_Name':['April Reiter','Emory Miller','David Ballin','Alice Trotter','Virginia Rios']}df = pd.DataFrame(data=data)print(df)
gives
Full_Name0 April Reiter1 Emory Miller2 David Ballin3 Alice Trotter4 Virginia Rios
Create a new column with initials
Now let's see step by step how to extract initials from the column Full_Name:
Step1: split first and last names using pandas.Series.str.split:
df['Full_Name'].str.split(expand=True)
gives
0 10 April Reiter1 Emory Miller2 David Ballin3 Alice Trotter4 Virginia Rios
Step 2: exatract first letter for each columns:
df['Full_Name'].str.split(expand=True).apply(lambda x : x.str[0])
gives
0 10 A R1 E M2 D B3 A T4 V R
Step 3: aggregate column 0 and 1:
df['Full_Name'].str.split(expand=True).apply(lambda x : x.str[0]).agg('.'.join, axis=1)
gives
0 A.R1 E.M2 D.B3 A.T4 V.Rdtype: object
Step 4: Let's create a new column to store the initials:
df['Initials'] = df['Full_Name'].str.split(expand=True).apply(lambda x : x.str[0]).agg('.'.join, axis=1)
gives
Full_Name Initials0 April Reiter A.R1 Emory Miller E.M2 David Ballin D.B3 Alice Trotter A.T4 Virginia Rios V.R
done !
