Home > Net >  Dictionary to DataFrame with multiple columns and one row
Dictionary to DataFrame with multiple columns and one row

Time:08-09

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:

{'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

CodePudding user response:

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

CodePudding user response:

Make the dictionary data into a series, pass that to Dataframe, and then reset to the transform.

Showing how this would work as a one-liner:

data = {'Pclass': 3, 'Sex': 0, 'SibSp': 1, 'Parch': 0, 'Age': 50.0, 'Fare': 20.0, 'Embarked': 0}
df = pd.DataFrame(pd.Series(data)).T
   Pclass  Sex  SibSp  Parch   Age  Fare  Embarked
0     3.0  0.0    1.0    0.0  50.0  20.0       0.0

However, the drawback to this is that the number formats haven't been preserved with respect to ints and floats.

  • Related