split strings from a column in separate columns

Viewed 127

I am trying to split string values from a column, in as many columns as strings are in each row. I am creating a new dataframe with three columns and I have the string values in the third column, I want to split in new columns (which already have headers) but the numbers of strings which are separated by semicolon, is different in each row If I use this code:

df['string']= df['string'].str.split(';', expand=True)

then I will have left only one value in the column while the rest of the string values will not be split but eliminated.

Cal u advice on how this line of code should be modified in order to have the right output? many thanks in advance

2 Answers

Then we do

df['string']= df['string'].str.split(';', expand=True).str[0]

Instead of overwriting the original column, you can take the result of split and join with original DataFrame

df = pd.DataFrame({'my_string':['car;war;bus','school;college']})
df = df.join(df['my_string'].str.split(';',expand=True))
print(df)
        my_string       0        1     2
0     car;war;bus     car      war   bus
1  school;college  school  college  None
Related