Personnaliser les préférences

Nous utilisons des cookies pour vous aider à naviguer efficacement et à exécuter certaines fonctions. Vous trouverez ci-dessous des informations détaillées sur tous les cookies sous chaque catégorie de consentement.

Les cookies classés comme « Nécessaires » sont stockés sur votre navigateur car ils sont essentiels pour activer les fonctionnalités de base du site.... 

Toujours actif

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Aucun cookie à afficher.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Aucun cookie à afficher.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Aucun cookie à afficher.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Aucun cookie à afficher.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

Aucun cookie à afficher.

Comment convertir un DataFrame Pandas en JSON



Souvent, vous pourriez être intéressé par la conversion d’un DataFrame pandas au format JSON.

Heureusement, cela est facile à faire en utilisant la fonction to_json() , qui vous permet de convertir un DataFrame en chaîne JSON avec l’un des formats suivants :

  • ‘split’ : dict comme {‘index’ -> [index], ‘colonnes’ -> [colonnes], ‘données’ -> [valeurs]}
  • ‘records’ : liste comme [{column -> value}, … , {column -> value}]
  • ‘index’ : dict comme {index -> {colonne -> valeur}}
  • ‘colonnes’ : dict comme {colonne -> {index -> valeur}}
  • ‘values’ : juste le tableau de valeurs
  • ‘table’ : dict comme {‘schema’ : {schéma}, ‘data’ : {data}}

Ce didacticiel montre comment convertir un DataFrame dans chacun des six formats à l’aide du DataFrame pandas suivant :

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 19],
                   'assists': [5, 7, 7, 12]})  

#view DataFrame
df

        points	assists
0	25	5
1	12	7
2	15	7
3	19	12

Méthode 1 : « Diviser »

df.to_json(orient='split')

{
   "columns": [
      "points",
      "assists"
   ],
   "index": [
      0,
      1,
      2,
      3
   ],
   "data": [
      [
         25,
         5
      ],
      [
         12,
         7
      ],
      [
         15,
         7
      ],
      [
         19,
         12
      ]
   ]
}

Méthode 2 : « Enregistrements »

df.to_json(orient='records')

[
   {
      "points": 25,
      "assists": 5
   },
   {
      "points": 12,
      "assists": 7
   },
   {
      "points": 15,
      "assists": 7
   },
   {
      "points": 19,
      "assists": 12
   }
] 

Méthode 3 : « Index »

df.to_json(orient='index') 

{
   "0": {
      "points": 25,
      "assists": 5
   },
   "1": {
      "points": 12,
      "assists": 7
   },
   "2": {
      "points": 15,
      "assists": 7
   },
   "3": {
      "points": 19,
      "assists": 12
   }
}

Méthode 4 : « Colonnes »

df.to_json(orient='columns') 

{
   "points": {
      "0": 25,
      "1": 12,
      "2": 15,
      "3": 19
   },
   "assists": {
      "0": 5,
      "1": 7,
      "2": 7,
      "3": 12
   }
}

Méthode 5 : « Valeurs »

df.to_json(orient='values') 

[
   [
      25,
      5
   ],
   [
      12,
      7
   ],
   [
      15,
      7
   ],
   [
      19,
      12
   ]
]

Méthode 6 : « Tableau »

df.to_json(orient='table') 

{
   "schema": {
      "fields": [
         {
            "name": "index",
            "type": "integer"
         },
         {
            "name": "points",
            "type": "integer"
         },
         {
            "name": "assists",
            "type": "integer"
         }
      ],
      "primaryKey": [
         "index"
      ],
      "pandas_version": "0.20.0"
   },
   "data": [
      {
         "index": 0,
         "points": 25,
         "assists": 5
      },
      {
         "index": 1,
         "points": 12,
         "assists": 7
      },
      {
         "index": 2,
         "points": 15,
         "assists": 7
      },
      {
         "index": 3,
         "points": 19,
         "assists": 12
      }
   ]
}

Comment exporter un fichier JSON

Vous pouvez utiliser la syntaxe suivante pour exporter un fichier JSON vers un chemin de fichier spécifique sur votre ordinateur :

#create JSON file 
json_file = df.to_json(orient='records') 

#export JSON file
with open('my_data.json', 'w') as f:
    f.write(json_file)

Vous pouvez trouver la documentation complète de la fonction pandas to_json() ici .

Ajouter un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *