Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a table using dictionary on pandas with specified columns

everyone.

I need a help in creating the table with specified columns

Easy example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from collections import defaultdict
import pandas as pd
d = defaultdict(list)
mapp = {'A': 'Error 3231', 'B': 'Error 23143243', 'C': 'Error 3242e32'}

for i in ['A', 'B']:
    d[i].append(f'U1_{mapp[i]}')

for i in ['A', 'C']:
    d[i].append(f'R1_{mapp[i]}')

When I use df1 = pd.DataFrame.from_dict(d, orient='index') it creates

                   0              1
A      U1_Error 3231  R1_Error 3231
B  U1_Error 23143243           None
C   R1_Error 3242e32           None

But actually, I want to get another table like the below one:

                   U1                  R1
A       U1_Error 3231       R1_Error 3231
B   U1_Error 23143243                None
C                None    R1_Error 3242e32

The values U1 and R1 are fixed.

Thank you.

>Solution :

Convert d to create your dataframe. It is often preferable to reformat your data before creating your dataframe:

df = pd.Series({(k, v[:2]): v for k, l in d.items() for v in l}).unstack()
print(df)

# Output
                  R1               U1
A  R1_Error dsad2314  U1_Error 232324
B                NaN  U1_Error 232324
C  R1_Error dsad2314              NaN

Transformation:

# From
>>> dict(d)
{'A': ['U1_Error 232324', 'R1_Error dsad2314'],
 'B': ['U1_Error 232324'],
 'C': ['R1_Error dsad2314']}

# To
>>> {(k, v[:2]): v for k, l in d.items() for v in l}
{('A', 'U1'): 'U1_Error 232324',
 ('A', 'R1'): 'R1_Error dsad2314',
 ('B', 'U1'): 'U1_Error 232324',
 ('C', 'R1'): 'R1_Error dsad2314'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading