python - 如何在 Pandas DataFrame 中使用 json_normalize 访问特定字段

标签 python pandas dataframe

所以我有这个 Json:

"customerDetails": {
    "city": "John doe city",
    "countryCode": "NL",
    "email": "john@doe.com",
    "firstName": "John",
    "houseNumber": "31",
    "salutationCode": "03",
    "streetName": "John doe street",
    "surname": "Doe",
    "zipCode": "9999"
},
"shipmentDate": "2019-11-04T20:27:30+01:00",
"shipmentId": 688016123,
"shipmentItems": [
    {
        "ean": "87193266436",
        "fulfilmentMethod": "FBB",
        "latestDeliveryDate": "2019-11-05T00:00:00+01:00",
        "offerCondition": "NEW",
        "offerPrice": 43.0,
        "orderDate": "2019-11-04T17:02:07+01:00",
        "orderId": "26354945747",
        "orderItemId": "BFC000032457457",
        "quantity": 1,
        "title": "Cheese grater"
    }
],
"shipmentReference": "081234500913463469",

当我想从 customerDetails 获取数据框时,我使用这个:

df = pd.DataFrame.from_dict([data])

d = json_normalize(df['customerDetails'])

print(d)

这非常有效,但是当我尝试在 shipmentItems 上使用它时,我会抛出一个错误。如何解决此问题以从 shipmentItems 获取数据框中的正确列?

最佳答案

如果可能,请使用 json_normalize 而不使用 DataFrame 构造函数:

d = json_normalize(data['shipmentItems'])

print(d)
           ean fulfilmentMethod         latestDeliveryDate offerCondition  \
0  87193266436              FBB  2019-11-05T00:00:00+01:00            NEW   

   offerPrice                  orderDate      orderId      orderItemId  \
0        43.0  2019-11-04T17:02:07+01:00  26354945747  BFC000032457457   

   quantity          title  
0         1  Cheese grater  

关于python - 如何在 Pandas DataFrame 中使用 json_normalize 访问特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58787134/

相关文章:

python - 根据相似性百分比连接文件中的多个 seq

python - 如何在seaborn中对齐x标签和y标签?

python - Pandas 在使用 apply 方法时删除了 lambda

python - Pyinstaller --onefile模式,解包前如何向控制台写入消息

python - 从元组列表中,获取最接近给定值的元组

python - 在 RESTful Web 服务中,服务器需要很长时间才能响应是否可以接受?

python - 使用 Pandas 的 Groupby df 列

python - Pandas 数据框列的值作为列表

python - 将多索引/多级数据框减少为单索引、单级

读取R中的CSV作为data.frame