Repeat a column value

Viewed 63

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?

3 Answers
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)

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.

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
Related