簡體   English   中英

Python 將 Json 讀入 DataFrame

[英]Python read Json into DataFrame

假設我有以下 json 數據:

 [
    {
        "cust_Name": [
            "Nia Bernard",
            "Nicole",
            "Katelin"
        ],
        "cust_Rate": [
            "1.0 out of 5 stars",
            "4.0 out of 5 stars",
            "5.0 out of 5 stars"
        ],
        "date_comment": [
            "Reviewed in the United States on January 10, 2019",
            "Reviewed in the United States on December 18, 2018",
            "Reviewed in the United States on August 14, 2017"
        ]
    }
]

如何使用以下 output 將此 json 格式讀入數據幀:

cust_Name      cust_Rate            date_comment
Nia Bernard    1.0 out of 5 stars   Reviewed in the United States on January 10, 2019
Nicole         4.0 out of 5 stars   Reviewed in the United States on December 18, 2018
Katelin        5.0 out of 5 stars   Reviewed in the United States on August 14, 2017

謝謝

data=[
    {
        "cust_Name": [
            "Nia Bernard",
            "Nicole",
            "Katelin"
        ],
        "cust_Rate": [
            "1.0 out of 5 stars",
            "4.0 out of 5 stars",
            "5.0 out of 5 stars"
        ],
        "date_comment": [
            "Reviewed in the United States on January 10, 2019",
            "Reviewed in the United States on December 18, 2018",
            "Reviewed in the United States on August 14, 2017"
        ]
    }
]

現在只需使用 pandas 中的Dataframe()方法創建pandas :-

import pandas as pd

df=pd.DataFrame(data[0])

現在,如果您打印df您將獲得預期的 output:-

cust_Name           cust_Rate             date_comment
0   Nia Bernard     1.0 out of 5 stars    Reviewed in the United States on January 10, 2019
1   Nicole          4.0 out of 5 stars    Reviewed in the United States on December 18, ...
2   Katelin         5.0 out of 5 stars    Reviewed in the United States on August 14, 2017

屬性“orient”可能有一種更簡潔的方法,但這里有一種方法:

df_in = pd.read_json('your_file.json')
df = pd.DataFrame(columns=df_in.columns)
for col in df.columns:
    df[col] = df_in[col].values[0]
    
print(df)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM