Jstuff Jstuff - 1 year ago 93
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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download