Home > other >  I want to print cell value of a column one by one after comma
I want to print cell value of a column one by one after comma

Time:09-06

import pandas as pd


data = {'product_name': ['laptop,computer', 'printer,table', 'tablet,mobile', 'desk', 'chair,table'],
        'price': [1200, 150, 300, 450, 200]
        }

df_merge = pd.DataFrame(data)

I want to print data by using for loop 1st it should come laptop then computer then printer and so on. for example- enter image description here

I tried below lines of code but not getting what I want.

for i in (df_merge.product_name):
print(i)

CodePudding user response:

USING FOR LOOP Code:

for i in (df_merge.product_name):
    for s in i.split(','):
        print(s)

Output;

laptop
computer
printer
table
tablet
mobile
desk
chair
table

CodePudding user response:

You can use .str.split(',') and then .explode():

print(*df_merge["product_name"].str.split(",").explode(), sep="\n")

Prints:

laptop
computer
printer
table
tablet
mobile
desk
chair
table

If you want to explode whole dataframe:

df_merge["product_name"] = df_merge["product_name"].str.split(",")
df_merge = df_merge.explode("product_name")
print(df_merge)

Prints:

  product_name  price
0       laptop   1200
0     computer   1200
1      printer    150
1        table    150
2       tablet    300
2       mobile    300
3         desk    450
4        chair    200
4        table    200
  • Related