0

enter image description here

How do I split the comma-separated string to new columns

Expected output

    Source       Target      Weight
0  Majed Moqed  Majed Moqed      0
  • First `#Get each element into its column by spliting the existing single column` as follows `s=df['(Source,Target,Weight)'].str.split('\,', expand=True)` then `#Set columns` as follows `s.columns=list(df.columns.str.replace('[^A-Za-z\,]','', regex=True).str.split(','))[0]` print(s) – wwnde Dec 19 '21 at 00:56

3 Answers3

0

Try this:

df['Source'] = df['(Source, Target, Weight)'].split(',')[0]
df['Target'] = df['(Source, Target, Weight)'].split(',')[1]
df['Weight'] = df['(Source, Target, Weight)'].split(',')[2]
Muhammed Jaseem
  • 782
  • 6
  • 18
0

Try this:

col = '(Source, Target, Weight)'
df = pd.DataFrame(df[col].str.split(',').tolist(), columns=col[1:-1].split(', '))
0

You can also do:

col = '(Source, Target, Weight)'
df[col.strip('()').split(', ')] = df[col].str.split(',', expand=True)