In a Dataframe, there are two columns (From
and To
) with rows containing multiple numbers separated by commas and other rows that have only a single number and no commas. How to explode into their own rows the multiple comma-separated numbers while leaving in place and unchanged the rows with single numbers and no commas?
The code below works EXCEPT it turns all the single numbers with no commas into NaN
.
DT = DT.assign(To=DT['To'].str.split(',')).explode('To').reset_index(drop=True)
DT = DT.assign(From=DT['From'].str.split(',')).explode('From').reset_index(drop=True)
Thank you!
It's likely that the single numbers are int type, so you can try to convert them into string
DT.assign(To=DT['To'].astype(str).str.split(',')).explode('To', ignore_index=True)