簡體   English   中英

將Pandas數據框轉換為嵌套JSON的更快方法

[英]Faster way to convert Pandas dataframe into nested json

我有看起來像這樣的數據:

player, goals, matches
ronaldo, 10, 5
messi, 7, 9

我想將此數據幀轉換為嵌套的json,例如:

{
    "content":[
        {
            "player": "ronaldo",
            "events": {
                "goals": 10,
                "matches": 5
            }
        },
        {
            "player": "messi",
            "events": {
                "goals": 7,
                "matches": 9
            }
        }
    ]
}

這是我的代碼,使用列表理解:

df = pd.DataFrame([['ronaldo', 10, 5], ['messi', 7, 9]], columns=['player', 'goals', 'matches'])
d = [{'events': df.loc[ix, ['goals', 'matches']].to_dict(), 'player': df.loc[ix, 'player']} for ix in range(df.shape[0])]
j = {}
j['content'] = d

這行得通,但是當我有很多數據時,性能確實很慢。 有更快的方法嗎?

嘗試:

df.to_json(orient = "records")

問題是它沒有在事件列上堆積目標和匹配項,但我不確定是否可以不循環而完成

暫無
暫無

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

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