Home > Back-end >  Create column names for nested dictionary in pandas
Create column names for nested dictionary in pandas

Time:08-03

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.

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"]

CodePudding user response:

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

CodePudding user response:

One way to do is to use transform of the df:

pd.DataFrame(my_dict).T.reset_index().rename(columns={'index':'C1'})

or

pd.DataFrame(my_dict).T.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
  • Related