3

I have input dataframe in below format

enter image description here

I want the output in below format

enter image description here

Input data for referance

import pandas as pd
dfno = pd.DataFrame({'Nodes':['A','B','C'], 'Connections': ['Za,Eb', 'Qa,Rb', 'La,Mb']})

I tried below code to convert each value of both rows into list and then adding to dataframe. But it did not work. Here character in connection columns are getting split.

for index, row in dfno.iterrows():
    node = str(row['Nodes'])
    connec = list(str(row['Connections']))
    print(node)
    print(connec)

How to do this?

SoKu
  • 117
  • 7
  • You can refer [stack thread](https://stackoverflow.com/questions/12680754/split-explode-pandas-dataframe-string-entry-to-separate-rows) – Agnij Sep 29 '21 at 07:18

3 Answers3

3
import pandas as pd
dfno = pd.DataFrame({'Nodes':['A','B','C'], 'Connections': ['Za,Eb', 'Qa,Rb', 'La,Mb']})

for index, row in dfno.iterrows():
    node = str(row['Nodes'])
    connec = str(row['Connections']).split(',')
    print(node)
    print(connec)
1

You can do:

df["Connections"] = df["Connections"].str.split(",")
df = df.explode("Connections").reset_index(drop=True)

I hope that it can help you resolve the problem.

0

The best solution here is with explode:

dfno.assign(Connections=dfno['Connections'].str.split(',')).explode('Connections')

Output:

  Nodes Connections
0     A          Za
0     A          Eb
1     B          Qa
1     B          Rb
2     C          La
2     C          Mb
U13-Forward
  • 69,221
  • 14
  • 89
  • 114