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 column names for nested dictionary in pandas

I have a nested dictionary as below.

my_dic={'CELL1': {'C2': 'LOW', 'C3': 'HIGH', 'C4': 'Pass'}, 'CELL2': {'C2': 'LOW', 'C3': 'HIGH', 'C4': 'Pass'}, 'CELL3': {'C2': 'LOW', 'C3': 'HIGH', 'C4': 'Pass'}, 'CELL4': {'C2': 'LOW', 'C3': 'HIGH', 'C4': 'Pass'}, 'CELL5': {'C2': 'LOW', 'C3': 'HIGH', 'C4': 'Pass'}}

I am trying to print the data frame on to the console in the below format.

   C1     C2   C3      C4 
0  CELL1  LOW  HIGH   Pass
1  CELL2  LOW  HIGH   Pass
2  CELL3  LOW  HIGH   Pass
3  CELL4  LOW  HIGH   Pass
4  CELL5  LOW  HIGH   Pass
5  CELL5  LOW  HIGH   Pass

But when i try to overwrite the column names to what I want. I am getting the below error.

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

ValueError: Length mismatch: Expected axis has 0 elements, new values have 4 elements

I have tried the below code. Can someone help me out with this?

df_my =pd.DataFrame.from_dict(my_dic,orient = 'index').reset_index()
df_my.columns=["C1", "C2", "C3", "C4"]

>Solution :

You code should work, I would use:

df_my = (pd.DataFrame.from_dict(my_dic, orient='index')
           .rename_axis('C1').reset_index()
         )

output:

      C1   C2    C3    C4
0  CELL1  LOW  HIGH  Pass
1  CELL2  LOW  HIGH  Pass
2  CELL3  LOW  HIGH  Pass
3  CELL4  LOW  HIGH  Pass
4  CELL5  LOW  HIGH  Pass
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