Grabbing First Word In String Using Lambda X and Pandas

Viewed 4980

I have a Pandas Series that contains two words for each value, and would like to make each word its own separate Series, preferably with the white space trimmed.

Normally in Python if I wanted to do this I could do something like the following:

my_string = "my string"
first_word = my_string.split()[0].strip()

However, when I try and use a similar convention inside Pandas I don't get the results that I want.

The following code is not working for me:

data['New Series'] = data['Old Series'].apply(lambda x: x.split()[0].strip())

I'm getting the following error:

IndexError: list index out of range 

It's like the code thinks I'm dealing with an empty array. How could I perform this function using the lambda x convention in Python?

PS - I know I could probably make a separate function and then do data['Old Series'].apply(function_name), but I'd prefer to keep the code as short as possible.

2 Answers

I think ou need text data functions like str.split:

data['New Series'] = data['Old Series'].str.split().str[0].str.strip()

#seems strip is not necessary, str.split trim leader whitespaces
#data['New Series'] = data['Old Series'].str.split().str[0]

Sample:

data = pd.DataFrame([' my string', 'aa', '', ' my an aa'], columns=['Old Series'])
data['New Series'] = data['Old Series'].str.split().str[0]
print (data)

   Old Series New Series
0   my string         my
1          aa         aa
2                    NaN
3    my an aa         my

You can use the lambda function like this:

data['New Series'] = data['Old Series'].apply(lambda x: x.split()[0].strip() if x else None)
Related