Jstuff Jstuff - 3 months ago 9x
Python Question

Splitting a string in pandas and join it to the old data

What I am doing seems simple, but I can not figure it out.

I have dataframe with data such as

City State ZIP
Ames IA 50011-3617
Ankeny IA 50021

I want to split the zipcodes by
and save only the first ones in a new dataframe which has the old data and only the new zipcode. I tried to do the following.

data_short_zip = data
df = data['ZIP'].str.split('-').str[0]

This not only throws an error, but seems unpythonic. Is there a simple way to do this?

The output data would look like

City State ZIP
Ames IA 50011
Ankeny IA 50021


You can use str.split to split on your delimeter and then str[0] on the result to return the first split:

In [122]:
df['ZIP'] = df['ZIP'].str.split('-').str[0]

     City State    ZIP
0    Ames    IA  50011
1  Ankeny    IA  50021