YHKIM
YHKIM

Reputation: 1

How to separate string and add up to row of DataFrame?

I tried to use regex and pandas function but I could not this df make to like below table How can i make to this?

df=pd.DataFrame({'a':['COD21C0521/534/583/584','COD21C0540_1/587_1/588_1']},index=['AAA','BBB']) 
a
AAA COD21C0521
AAA COD21C0534
AAA COD21C0583
AAA COD21C0584
BBB COD21C0540_1
BBB COD21C0587_1
BBB COD21C0588_1

Upvotes: 0

Views: 37

Answers (1)

9769953
9769953

Reputation: 12201

Use a combination of str[:] (indexing), str.split and explode methods:

import pandas as pd

df = pd.DataFrame(
    {'a':['COD21C0521/534/583/584','COD21C0540_1/587_1/588_1']},
     index=['AAA','BBB']) 

s = df['a'].str[:7] + df['a'].str[7:].str.split('/').explode()
print(s)

yields

AAA      COD21C0521
AAA      COD21C0534
AAA      COD21C0583
AAA      COD21C0584
BBB    COD21C0540_1
BBB    COD21C0587_1
BBB    COD21C0588_1
Name: a, dtype: object

Be aware that you can't assign the result back to the dataframe (df['a'] = ...), since there are only two rows in the original dataframe, and seven in the output. Hence s for Series.

Upvotes: 1

Related Questions