Search code examples
pythonpandasdataframesplit

Pandas: Split Row in multiple Rows based on Delimiter in Specific Column


Say I have the following dataframe:

df = pd.DataFrame({
'ASSET_CLASS': ['Core',],
'SPLIT': ['0.6 Government / 0.4 Credit']})

display(df)

    ASSET_CLASS SPLIT
0   Core        0.6 Government / 0.4 Credit

My objective is to split the row into two rows by specifying the forward slash symbol as delimiter in column "SPLIT". Ideally, this is what I aim to obtain:

    ASSET_CLASS SPLIT
0   Core        0.6 Government
1   Core        0.4 Credit

Is there a way to achieve this using the explode function?


Solution

  • Use split and explode:

    df["SPLIT"] = df["SPLIT"].str.split(" / ")
    df = df.explode("SPLIT").reset_index(drop=True)
    
    >>> df
      ASSET_CLASS           SPLIT
    0        Core  0.6 Government
    1        Core      0.4 Credit