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

How to convert Pandas dataframe to a specific format

I have a pandas dataframe like below

    data = pd.DataFrame([
    {"name" : "c","email" : "edfr@test.com","ml_pred":"valid","hum_pred":"null","score":0.83},
    {"name" : "d","email" : "edsd@test.com","ml_pred":"invalid","hum_pred":"null","score":0.12}
])

How can this dataframe be converted to the following format

    [
        ({"email": {"$eq": "edfr@test.com"}},{"$set": {"ml_pred": "valid", "score": 0.83}}),
        ({"email": {"$eq": "edsd@test.com"}},{"$set": {"ml_pred": "invalid", "score": 0.12}})
   ]

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

>Solution :

You could use DataFrame.apply and construct a tuple for each row:

out = (data.apply(lambda x: ({"email": {"$eq": x["email"]}},
                             {"$set": {"ml_pred": x["ml_pred"], "score": x["score"]}}), 
                  axis=1).tolist())

Output:

[({'email': {'$eq': 'edfr@test.com'}}, {'$set': {'ml_pred': 'valid', 'score': 0.83}}),
 ({'email': {'$eq': 'edsd@test.com'}}, {'$set': {'ml_pred': 'invalid', 'score': 0.12}})]
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