SoKu
SoKu

Reputation: 127

Repeat a column value

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?

Upvotes: 3

Views: 108

Answers (3)

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.

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71560

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

Upvotes: 0

Powerful Lee
Powerful Lee

Reputation: 64

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)

Upvotes: 3

Related Questions