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

Dictionary to DataFrame with multiple columns and one row

I have got the following dataset:

pred_data = pd.DataFrame.from_dict(
    {
        "Pclass": [3],
        "Sex": [0],
        "SibSp": [1],
        "Parch": [0],
        "Age": [50.0],
        "Fare": [20.0],
        "Embarked": [0],
    }
)

   Pclass  Sex  SibSp  Parch   Age  Fare  Embarked
0       3    0      1      0  50.0  20.0         0

I have a POST endpoint in FastAPI where I want to get the data in the correct shape. When I turn my model into a dictionary, it looks like this:

@app.post("/")
async def predict(data: PassengerModel):
    print(data.dict())
    return data.dict()

It looks like this:

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

{'Pclass': 0, 'Sex': 0, 'SibSp': 0, 'Parch': 0, 'Age': 0.0, 'Fare': 0.0, 'Embarked': 0}

I guess I could look over the dictionary and turn each value into a list, but I guess there has to be a better solution to do this. I want the same one row with 7 columns like above. Is there a quick way without looping over keys etc.?

Thank you!

Edit: It has not to be the same as in the example above, I guess this is a pretty terrible solution?!

Expected Output:

Pandas DataFrame:

       Pclass  Sex  SibSp  Parch   Age  Fare  Embarked
    0       3    0      1      0  50.0  20.0         0

>Solution :

You can simply wrap the dictionary in a list and use the DataFrame constructor:

d = {'Pclass': 0, 'Sex': 0, 'SibSp': 0, 'Parch': 0, 'Age': 0.0,
     'Fare': 0.0, 'Embarked': 0}

df = pd.DataFrame([d])

output:

   Pclass  Sex  SibSp  Parch  Age  Fare  Embarked
0       0    0      0      0  0.0   0.0         0
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