How do I derive the surnames of everyone whose first names have a condition in a pandas data frame?

50 Views Asked by At

Using pandas, I want to derive a last name column for a set of first names that are 4 or more characters long.

I have tried these:

data = pd.read_csv("Data.csv")
#split the EmployeeName into firstname and lastname
flname = data['EmployeeName'].str.split(expand=True)

#add first name column to data frame
data['FirstName'] = flname[0]

#apply condition on first name
dfname = data['FirstName'].apply(lambda x:x if len(x) \> 4 else None)
dfname = dfname.dropna()

#add last name and new first name columns to data frame
data['LastName'] = flname[0]
data['NewFirstName'] = dfname

#This is the wrong bit that throws an error
derived_name = data.apply(lambda x:x if data\['FirstName'\] in data\['NewFirstName'\] else None)
derived_name.dropna()

#TypeError: unhashable type: 'Series'

#Are there shorter ways of writing these code lines with pandas?

2

There are 2 best solutions below

2
Bumze On

I resolved this with answer to question 1387.

df = data[data['NewFirstName'].notna()]
df['LastName']

Thanks all. But are there shorter ways to answer the question?

1
Ajey Dikshit On

Splitting the data

data[['Firstname', 'Lastname']] = data['EmployeeName].str.split(expand=True)

After splitting the name columns, you should use masking as it makes this very easy.

data[data['Firstname'].str.len() >= 4]['Lastname']

should give you the desired output