[SOLVED] TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid I got this error


giving a unique code by seeing the first column string and the second columns string and whenever the first column string change it starts from 1

enter image description here

i use this code

dfs = dict(tuple(df.groupby('colummen1')))
for _, df in dfs.items():

 df['id'] = df.groupby(['colummen1','colummun2']).ngroup()  

dfs = [df[1] for df in dfs]
df = pd.concat(dfs)

but I got the flowing error
enter image description here


Your code can be updated in the following way:

import pandas as pd

# set data
data = {"colummen1": ["Kenbele1", "Kenbele1", "Kenbele1", "Kenbele1", "Kenbele2", "Kenbele2", "Kenbele2", "Kenbele2"], 
        "colummun2": ["Commutity1", "Commutity2", "Commutity3", "Commutity4", "Commutity1", "Commutity2", "Commutity3", "Commutity4"]}

# create dataframe
df = pd.DataFrame(data)

dfs = df.groupby('colummen1')

dfs_updated = []

for _, df in dfs:
    df['id'] = df.groupby(['colummen1','colummun2']).ngroup()+1
df_new = pd.concat(dfs_updated)



enter image description here

Answered By – GreyMurav

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *