0

I've seen some similar problems on stack, but not exactly like this. I appreciate if you could share a way to turn df into df2.

df = pd.DataFrame({'zips': ['11229 11226 11225', '90291 90293 90292'],
                  'lat': [40.6943, 34.1139],
                  'lng': [-73.9249, -118.4068]})


df2 = pd.DataFrame({'zips': [11229, 11226, 11225, 90291, 90293, 90292],
                  'lat': [40.6943, 40.6943, 40.6943, 34.1139, 34.1139, 34.1139],
                  'lng': [-73.9249, -73.9249, -73.9249, -118.4068, -118.4068, -118.4068]})```

Thanks!
1
  • 3
    split and then explode: df.assign(zips = df.zips.str.split(' ')).explode('zips') Commented May 12, 2021 at 0:25

1 Answer 1

2

You can first split the values in zips column on space which will give a list, then just use explode

df['zips'] = df['zips'].str.split()
df.explode('zips')

OUTPUT:

    zips      lat       lng
0  11229  40.6943  -73.9249
1  11226  40.6943  -73.9249
2  11225  40.6943  -73.9249
3  90291  34.1139 -118.4068
4  90293  34.1139 -118.4068
5  90292  34.1139 -118.4068

You can further change the data type of zips column to integer if you wish to by type casting

df['zips'] = df['zips'].astype(int)
Sign up to request clarification or add additional context in comments.

Comments

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.