0

I have dataframe as below with NaN value.

Category,Type,Capacity,Efficiency  
Chiller,ChillerA,1000,6.0  
Chiller,ChillerB,2000,5.5  
Cooling Tower,Cooling TowerA,1000,NaN  
Cooling Tower,Cooling TowerB,2000,NaN  

I want to convert this pandas dataframe to below json format.
Can anyone tell me how to implement this?

{
    "Chiller":{
        "ChillerA":{
            "Capacity":1000,
            "Efficiency":6.0
        },
        "ChillerB":{
            "Capacity":2000,
            "Efficiency":5.5
        },
    },
    "Cooling Tower":{
        "Cooling TowerA":{
            "Capacity":1000 <=Will not include efficiency because efficiency was NaN for this.

        },
        "Cooling TowerB":{
            "Capacity":2000
        },
    },
}

1 Answer 1

2

This is a very robust solution that will get you to desired output using nested dict comprehension:

df = df.set_index(['Category', 'Type'])
{level: {chiller: {name: value for name, value in values.items() if not np.isnan(value)} for chiller, values in df.xs(level).to_dict('index').items()} for level in df.index.levels[0]}
#{'Cooling Tower':
#    {'Cooling TowerA':
#       {'Capacity': 1000.0},
#    'Cooling TowerB':
#        {'Capacity': 2000.0}},
# 'Chiller':
#    {'ChillerA': {'Efficiency': 6.0, 'Capacity': 1000.0},
#     'ChillerB': {'Efficiency': 5.5, 'Capacity': 2000.0}}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.