Jure Stabuc
Jure Stabuc

Reputation: 569

Pandas - splitting a string in some cells

I have a column and some of the cells have multiple values I want to split, so they get into a new row.

This a sample from my dataframe:

        index   ref_made_call
0   58  Sean Wright
1   115 Nick Buchert
2   191 James Williams
3   196 Jason Phillips
4   266 Scott Wall
5   272 Curtis Blair
6   390 Bennett Salvatore
7   490 Derrick Stafford
8   600 Kevin Cutler
9   683 Josh Tiven
10  816 Bennett Salvatore
11  1014    Joe Crawford
12  1255    Scott Foster,Sean Wright

I want to split Scott Foster,Sean Wright so the dataframe would look like:

        index   ref_made_call
0   58  Sean Wright
1   115 Nick Buchert
2   191 James Williams
3   196 Jason Phillips
4   266 Scott Wall
5   272 Curtis Blair
6   390 Bennett Salvatore
7   490 Derrick Stafford
8   600 Kevin Cutler
9   683 Josh Tiven
10  816 Bennett Salvatore
11  1014    Joe Crawford
12  1255    Scott Foster
13       Sean Wright

I already looked into this but it doesn't make what I want.

Thanks for any help!

Upvotes: 1

Views: 321

Answers (1)

piRSquared
piRSquared

Reputation: 294218

using str.split + stack

df.set_index('index') \
    .ref_made_call.str.split(',', expand=True) \
    .stack().reset_index(-1, drop=True) \
    .reset_index(name='ref_made_call')

    index      ref_made_call
0      58        Sean Wright
1     115       Nick Buchert
2     191     James Williams
3     196     Jason Phillips
4     266         Scott Wall
5     272       Curtis Blair
6     390  Bennett Salvatore
7     490   Derrick Stafford
8     600       Kevin Cutler
9     683         Josh Tiven
10    816  Bennett Salvatore
11   1014       Joe Crawford
12   1255       Scott Foster
13   1255        Sean Wright

Upvotes: 1

Related Questions