Home > other >  Repeat a column value
Repeat a column value

Time:09-30

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?

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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