12

Suppose I have a DataFrame with 100k rows and a column name. I would like to split this name into first and last name as efficiently as possibly. My current method is,

def splitName(name):
  return pandas.Series(name.split()[0:2])

df[['first', 'last']] = df.apply(lambda x: splitName(x['name']), axis=1)

Unfortunately, DataFrame.apply is really, really slow. Is there anything I can do to make this string operation nearly as fast as a numpy operation?

Thanks!

1

1 Answer 1

23

Try (requires pandas >= 0.8.1):

splits = x['name'].split()
df['first'] = splits.str[0]
df['last'] = splits.str[1]
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! Didn't know about this addition.
Interestingly, this question is identical to this later one but the response has no mention of Series.split(). Has it been removed from pandas?
It is now available as Series.str.split()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.