如何将FastAPI接收的单值字典快速转为单行多列Pandas DataFrame?
问题描述
我有如下单行Pandas DataFrame的示例格式:
pred_data = pd.DataFrame.from_dict( { "Pclass": [3], "Sex": [0], "SibSp": [1], "Parch": [0], "Age": [50.0], "Fare": [20.0], "Embarked": [0], } )
输出的DataFrame结构:
Pclass Sex SibSp Parch Age Fare Embarked 0 3 0 1 0 50.0 20.0 0
我在FastAPI中搭建了POST接口,接收PassengerModel模型后转成字典,代码如下:
@app.post("/") async def predict(data: PassengerModel): print(data.dict()) return data.dict()
得到的字典格式为:
{'Pclass': 0, 'Sex': 0, 'SibSp': 0, 'Parch': 0, 'Age': 0.0, 'Fare': 0.0, 'Embarked': 0}
我需要把这个字典转成上述示例的单行7列DataFrame,但不想遍历字典的键,寻求更优实现方案。
解决方案
不用遍历键的话,有几种简洁的实现方式:
方法1:将字典包装为列表传入DataFrame
直接把整个字典放到列表中,Pandas会自动识别为单行数据:
import pandas as pd data_dict = {'Pclass': 0, 'Sex': 0, 'SibSp': 0, 'Parch': 0, 'Age': 0.0, 'Fare': 0.0, 'Embarked': 0} df = pd.DataFrame([data_dict])
这种方式最直观,无需额外参数,Pandas会自动匹配列名和对应值。
方法2:使用from_dict并指定orient='index'后转置
利用from_dict的orient参数,先按索引构建DataFrame再转置:
df = pd.DataFrame.from_dict(data_dict, orient='index').T
orient='index'会把字典的键作为行索引,值作为列,转置后就得到我们需要的单行结构。
方法3:通过Series转换
先把字典转为Series,再转为DataFrame:
df = pd.Series(data_dict).to_frame().T
Series的索引对应字典的键,转置后即可得到单行DataFrame。
这三种方法都不需要手动遍历字典的键,直接完成格式转换,最终输出的DataFrame结构和示例完全一致。
内容的提问来源于stack exchange,提问作者Data Mastery
相关产品推荐
相关产品推荐

