AttributeError: 'tuple' object has no attribute 'values' getting error while concatenate multiple nested dictionaries using single function

Question:

I’m trying the function to create the single dataframe using convert_df using pandas showing following error.
I have to dataframe df, df1 want to convert into single dataframe


df = {1 : {'tp': 26, 'fp': 112},
2 : {'tp': 26, 'fp': 91},
3 : {'tp': 23, 'fp': 74}}

df1 = {1 : {'tp1': 2633, 'fp1': 34},
2 : {'tp1': 333, 'fp1': 9341},
3 : {'tp1': 335, 'fp1': 34}}

def convert_df(*dic):
    df = pd.DataFrame.from_dict(dic,orient='index')
    
    return df
d, d1 = convert_df([df,df1])

the error is
enter image description here

expected output like
enter image description here

Asked By: Sushil Kokil

||

Answers:

Not sure what you exactly want, but if I guess correctly:

d1 = {1 : {'tp': 26, 'fp': 112},
      2 : {'tp': 26, 'fp': 91},
      3 : {'tp': 23, 'fp': 74}}

d2 = {1 : {'tp': 2633, 'fp': 34},
      2 : {'tp': 333, 'fp': 9341},
      3 : {'tp': 335, 'fp': 34}}

dicts = [d1, d2]

def convert_df(dic):
    return pd.DataFrame.from_dict(dic, orient='index')

df = pd.concat([convert_df(d) for d in dicts])
# or
# df = pd.concat(map(convert_df, dicts), axis=1)

print(df)

Or maybe:

def convert_df(*dicts):
    return pd.concat([pd.DataFrame.from_dict(d, orient='index')
                      for d in dicts], axis=1)

df = convert_df(dicts)

output:

   tp   fp    tp    fp
1  26  112  2633    34
2  26   91   333  9341
3  23   74   335    34
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.