How to use json_normalize in Polars

Polars Code Academy
17 Jul 202410:24

Summary

TLDRDans cette vidéo, nous explorons la fonction Json normalize de Polars, introduite dans la version 1.0. Contrairement aux autres fonctions de lecture de JSON, elle permet de transformer des données JSON imbriquées en un format tabulaire. L'exemple montre comment charger un fichier JSON dans un dictionnaire Python puis l'utiliser avec la fonction Json normalize de Polars, en comparant avec l'approche de pandas. Nous abordons également les types de données mixtes et fournissons des solutions pour les gérer. La vidéo se termine par des astuces pour manipuler ces données efficacement avec Polars.

Takeaways

  • 🔄 La fonction Json normalize de Polars a été introduite dans la version 1.0 et est utilisée pour aplatir les données JSON en format tabulaire.
  • 📚 Avant d'utiliser Json normalize, il est nécessaire de lire le fichier JSON ou la chaîne JSON en un dictionnaire Python avec la bibliothèque JSON intégrée.
  • 📊 Json normalize est principalement utilisée pour traiter des fichiers JSON locaux non normalisés ou des données JSON imbriquées provenant d'une API.
  • 🚫 Contrairement aux fonctions d'entrée comme read_json et scan_json, Json normalize ne lit pas directement les données JSON dans un dataframe.
  • 🔧 La fonction Json normalize est stricte par défaut, ce qui signifie qu'elle ne tolère pas les types de données mixtes, mais cela peut être modifié en paramétrant strict à faux.
  • 📈 L'utilisation de Json normalize permet de transformer des données JSON en colonnes avec des noms longs, où les noms reflètent les chemins vers les valeurs dans la structure JSON.
  • 📊 En cas de valeurs imbriquées, les fonctions normalisent uniquement les paires clé-valeur et placent les listes dans le dataframe.
  • 🆚 La fonction Json normalize de Pandas est différente, ne nécessitant pas de paramètre strict et gère les types de données mixtes différemment.
  • 🔑 Avec Pandas, on peut utiliser l'argument record_path pour créer un nouveau dataframe basé sur un chemin spécifique dans les données JSON.
  • 🛠️ Dans Polars, pour obtenir des informations similaires à celles obtenues avec record_path dans Pandas, il faut indexer directement l'objet JSON après avoir utilisé Json normalize.

Q & A

  • Quelle est la fonctionnalité principale de la fonction Json normalize dans Polars?

    -La fonction Json normalize dans Polars a pour principal objectif de transformer les données JSON en les aplatissant dans un format tabulaire, ce qui est utile pour lire des fichiers JSON locaux non normalisés ou pour traiter des données JSON imbriquées provenant d'une API.

  • Pourquoi la fonction Json normalize n'est-elle pas considérée comme une fonction IO dans Polars?

    -La fonction Json normalize n'est pas considérée comme une fonction IO car elle ne lit pas directement les données JSON dans un dataframe. Au lieu de cela, il est nécessaire de lire le fichier JSON ou la chaîne JSON dans un dictionnaire Python en utilisant la bibliothèque JSON intégrée.

  • Quelle est la différence entre 'non-normalisé' et 'imbriqué' dans le contexte de la vidéo?

    -Dans le contexte de la vidéo, 'non-normalisé' et 'imbriqué' sont utilisés de manière interchangeable pour décrire les données JSON qui ont une structure complexe avec des niveaux imbriqués de données. Ces termes s'opposent à 'normalisé' et 'plat', qui décrivent des données JSON dans un format simple et sans imbrication.

  • Quels sont les autres fonctions Polars que l'on peut utiliser pour lire des données JSON si elles sont déjà dans un format plat?

    -Si les données JSON sont déjà dans un format plat, on peut utiliser d'autres fonctions telles que 'read_json' et 'scan_json' dans Polars pour les lire.

  • Comment importer les données JSON dans un dictionnaire Python à l'aide de la bibliothèque JSON intégrée?

    -Pour importer des données JSON dans un dictionnaire Python, on utilise la méthode 'json.load' en ouvrant le fichier JSON avec 'open' et en passant le chemin du jeu de données, puis en lisant le fichier avec le caractère 'r'.

  • Quelle est la différence entre la fonction Json normalize dans Polars et celle dans Pandas?

    -La fonction Json normalize dans Polars a un paramètre 'strict' qui permet de gérer les types de données mixtes, contrairement à Pandas qui ne possède pas ce paramètre et qui ne s'inquiète pas des types de données mixtes.

  • Comment Polars gère-t-il les types de données mixtes lors de l'utilisation de la fonction Json normalize?

    -Dans Polars, on peut gérer les types de données mixtes en définissant le paramètre 'strict' sur 'false' lors de l'utilisation de la fonction Json normalize.

  • Quelle est la méthode pour visualiser les cinq premières lignes d'un dataframe dans Polars?

    -Pour visualiser les cinq premières lignes d'un dataframe dans Polars, on utilise la méthode 'head' en tapant 'DF.head()' où 'DF' est le nom du dataframe.

  • Comment accéder aux valeurs imbriquées dans un dataframe Polars après avoir utilisé la fonction Json normalize?

    -Pour accéder aux valeurs imbriquées dans un dataframe Polars après avoir utilisé la fonction Json normalize, on peut indexer directement l'objet en utilisant les chemins de clés correspondants, par exemple 'meta["view"]["columns"]'.

  • Quel est le problème rencontré lors de l'indexation des données dans Polars et comment les développeurs de Polars ont-ils suggéré de le résoudre?

    -Le problème rencontré lors de l'indexation des données dans Polars était dû aux types de données mixtes, ce qui causait un affichage bizarre des données. Les développeurs de Polars ont suggéré d'utiliser la fonction 'dataframe' avec l'orientation 'row' pour contourner ce problème.

Outlines

00:00

📊 Introduction à la fonction Json Normalize de Polars

Dans le premier paragraphe, l'hôte du tutoriel introduit la fonction Json Normalize de Polars, qui est disponible depuis la version 1.0. Cette fonction permet de transformer des données JSON en format tabulaire en les aplatissant. Elle est particulièrement utile pour lire des fichiers JSON locaux non normalisés ou pour traiter des données JSON imbriquées provenant d'une API. L'hôte souligne que Json Normalize n'est pas considérée comme une fonction d'entrée, car elle ne lit pas directement les données JSON dans un dataframe. Au lieu de cela, il est nécessaire de lire le fichier JSON ou la chaîne JSON dans un dictionnaire Python en utilisant la bibliothèque Json intégrée. L'hôte explique ensuite les étapes pour utiliser cette fonction, en commençant par l'importation des bibliothèques nécessaires, puis en chargeant le fichier JSON dans un dictionnaire Python. Il mentionne également les paramètres de la fonction Json Normalize, notamment le paramètre 'strict', qui est utilisé pour gérer les types de données mixtes.

05:00

🔍 Comparaison entre Polars et Pandas pour la normalisation de JSON

Le deuxième paragraphe se concentre sur la comparaison de la fonction Json Normalize entre Polars et Pandas. L'hôte montre comment utiliser la fonction Json Normalize dans Polars et Pandas pour aplatir des données JSON imbriquées. Il souligne que les deux fonctions flattennent la structure JSON en créant de longs noms de colonnes qui représentent les chemins vers les valeurs. Cependant, il note que Polars et Pandas gèrent légèrement différemment les types de données mixtes. L'hôte explique ensuite comment utiliser l'argument 'record path' dans Pandas pour créer un nouveau dataframe basé sur un chemin spécifique dans les données JSON. Il compare ce processus à la méthode utilisée dans Polars, qui nécessite d'indexer directement l'objet pour obtenir les mêmes informations.

10:02

🛠 Résolution des problèmes de types de données mixtes avec Json Normalize

Dans le troisième paragraphe, l'hôte aborde les problèmes rencontrés avec les types de données mixtes lors de l'utilisation de la fonction Json Normalize dans Polars. Il mentionne qu'il a discuté avec les développeurs de Polars à ce sujet et qu'ils ont suggéré une solution alternative. L'hôte montre comment utiliser la fonction 'dataframe' de Polars pour créer un dataframe avec les données désirées, en orientant les données en ligne. Il conclut en exprimant l'espoir que des améliorations seront apportées à la fonction Json Normalize pour résoudre ces problèmes et en invitant les spectateurs à poser des questions ou à partager des commentaires.

Mindmap

Keywords

💡Polar

Polar est un framework de données utilisé pour l'analyse des données. Dans le script, Polar est mentionné comme l'outil principal pour montrer comment utiliser la fonction 'Json normalize'. Cela indique que le thème de la vidéo est centré sur l'utilisation de cette fonction spécifique dans le cadre de Polar pour traiter les données JSON.

💡Json normalize

La fonction 'Json normalize' est une fonctionnalité de Polar qui permet de transformer des données JSON en format tabulaire en les aplatissant. Dans le script, cette fonction est abordée en détail, expliquant comment elle est utilisée pour lire des fichiers JSON locaux ou des données imbriquées provenant d'une API, ce qui est crucial pour la compréhension de la manipulation de données JSON dans Polar.

💡Version 1.0

La version 1.0 de Polar est mentionnée comme la version minimale requise pour utiliser la fonction 'Json normalize'. Cela suggère que la fonctionnalité est récente et que les utilisateurs devraient s'assurer d'utiliser une version à jour de Polar pour profiter de cette fonctionnalité.

💡Python dictionary

Un 'Python dictionary' est un type de données en Python qui stocke des paires clé-valeur. Dans le script, il est expliqué que les données JSON doivent d'abord être lues en tant que 'Python dictionary' avant d'utiliser la fonction 'Json normalize', ce qui est un pas essentiel dans le processus de normalisation des données JSON dans Polar.

💡Tabular format

Le format tabulaire est un format de données structuré où les informations sont organisées en lignes et colonnes. Le script explique que la fonction 'Json normalize' est utilisée pour transformer des données JSON en format tabulaire, ce qui est utile pour l'analyse et la manipulation ultérieures des données.

💡Nested Json data

Les données JSON imbriquées font référence à des structures de données JSON où des objets ou des tableaux sont contenus dans d'autres objets ou tableaux. Le script mentionne que la fonction 'Json normalize' est particulièrement utile pour traiter ces types de données, ce qui est un défi commun lors du traitement des données JSON.

💡Strict parameter

Le paramètre 'strict' est mentionné dans le contexte de la fonction 'Json normalize' pour gérer les types de données mixtes. Dans le script, il est expliqué que ce paramètre peut être ajusté pour permettre la construction d'un DataFrame Polar même en présence de types de données mixtes, ce qui est un aspect important de la personnalisation de la fonction.

💡Pandas

Pandas est une bibliothèque de manipulation de données en Python qui est largement utilisée pour l'analyse de données. Dans le script, Pandas est comparé à Polar en ce qui concerne la fonctionnalité 'Json normalize', montrant comment les deux outils peuvent être utilisés pour atteindre le même objectif de normalisation des données JSON.

💡Record path

Le 'record path' est un argument utilisé dans la fonction 'Json normalize' de Pandas pour indiquer le chemin d'accès à un objet JSON complexe. Dans le script, il est expliqué comment l'utiliser pour créer un nouveau DataFrame basé sur un chemin spécifique, ce qui est une fonctionnalité importante pour la manipulation des données imbriquées.

💡Dataframe

Un 'dataframe' est une structure de données utilisée dans Polar et Pandas pour représenter des tables de données. Dans le script, la création et la manipulation de dataframes sont des tâches clés qui sont abordées lors de la normalisation des données JSON, montrant comment les données peuvent être organisées et analysées.

Highlights

Introduction to Polar's Json normalize function, available from version 1.0.

Json normalize is not an IO function but is used immediately after data is read into Python.

Json normalize transforms data by flattening nested Json into a tabular format.

Use case scenarios for Json normalize include reading local non-normalized Json files and receiving nested Json data from APIs.

Comparison between non-normalized nested data and normalized flat data in Json processing.

Demonstration of importing the Json library and Polars library in Python.

Loading a large electric vehicles Json file into a Python dictionary.

Using pl.Json_normalize to flatten Json data with a strict parameter set to false for mixed data types.

Displaying the flattened data frame using the head method.

Comparison with Pandas' Json normalize function, which does not have a strict parameter.

Visual differences in data frames between Polars and Pandas, including data type display.

Explanation of long column names resulting from flattened Json structure.

Handling nested items in both Polars and Pandas by accessing values and creating separate data frames.

Using the record_path parameter in Pandas to access nested data.

Direct indexing in Polars to achieve similar results as Pandas' record_path parameter.

Challenges with mixed data types in Polars' Json normalize function and a workaround suggested by the developers.

Final demonstration of using pl.dataframe with the orient parameter to resolve issues with mixed data types.

Conclusion and invitation for questions or comments from the audience.

Transcripts

play00:04

welcome back in this video we're going

play00:06

to show you how to use the polar's Json

play00:09

normalized function now this function

play00:11

was released in polar's version 1.0 so

play00:13

if you don't have that version or a more

play00:15

recent version installed on your

play00:17

computer you'll definitely need to

play00:18

upgrade that first in order to use it

play00:22

with that said let's give a brief

play00:23

introduction into what Json normalize

play00:25

does and how it's different from other

play00:27

Json functions you might see in polers

play00:30

Json normalize is not technically

play00:32

considered an IO function that's because

play00:35

you are not directly reading Json data

play00:37

into a data frame when you use it

play00:39

instead you first need to read your Json

play00:41

file or Json string into a python

play00:44

dictionary using the built-in Json

play00:46

library that said I unofficially

play00:49

consider Json normalize an input

play00:51

function because you utilize it almost

play00:53

immediately after the data is read into

play00:55

python now the primary purpose of Json

play00:58

normalize is to transform Jason data by

play01:01

flattening it into a tabular format this

play01:04

comes in handy in a number of

play01:05

circumstances including when you need to

play01:07

read local non-normalized Json files or

play01:10

when receiving nested Json data from an

play01:13

API you'll notice that I use

play01:16

non-normalized and nested

play01:18

interchangeably you can also utilize

play01:20

normalized and flat interchangeably when

play01:24

your Json data is in a flat non- nested

play01:26

format you can use other functions like

play01:29

read Json

play01:30

and scan Json but these functions are

play01:33

absolutely useless if your data is not

play01:36

normalized with that said let's dive

play01:38

into implementing the Json normalized

play01:41

function okay so we're going to start by

play01:43

importing

play01:46

Json and we got to import

play01:51

polers as

play01:53

PL and I'm actually going to go ahead

play01:55

and just run

play01:56

that so now we have our libraryi in here

play01:59

and and that'll now enable us to get

play02:02

some help when we're kind of typing out

play02:03

some of these

play02:04

functions uh Next Step we're going to

play02:06

import our data so we have this electric

play02:08

vehicles Json file that we're going to

play02:10

use I won't open it because it's rather

play02:12

large and it might take a lot of memory

play02:14

so we're going to go ahead now and just

play02:16

upload that or load that into python

play02:19

dictionary so we're going to say f is

play02:21

equal to

play02:23

open and then we're going to type the

play02:25

path to our data set and one thing that

play02:27

you can do is just drag it and then hold

play02:30

the shift key and that should put it in

play02:31

there do need to close it in some quotes

play02:35

there and then the last thing I'm going

play02:38

to do is just make it so that we are

play02:40

reading this file using that R uh

play02:43

character there okay next step I'm going

play02:46

to type data and set it equal to

play02:50

json. load and so this is where we're

play02:52

going to load our Json file make it a

play02:55

python

play02:56

dictionary and that is how we're going

play02:59

to get that initial dictionary in and

play03:01

then we're going to go ahead and import

play03:04

or excuse me we're going to go ahead and

play03:07

now use the function so we're going to

play03:08

type

play03:09

pl. Json

play03:11

normalize and then we just need to pass

play03:14

our data in

play03:15

here and so by default polers is going

play03:18

to be strict about how it constructs the

play03:20

data frame meaning that it won't allow

play03:22

for mixed data types and I already know

play03:25

that this data that we're working with

play03:26

has some mixed data types so I'm going

play03:28

to go ahead and set another parameter in

play03:30

here that is the strict parameter I'm

play03:34

going to set that equal to

play03:37

false and we're going to go ahead and

play03:39

address the mixed data types A little

play03:42

bit later let's go ahead and display our

play03:44

data here I'm going to go ahead and type

play03:46

DF and then just select the top five by

play03:49

typing the head

play03:50

method and when we run

play03:52

that we get a new data frame that's been

play03:57

flattened now I want to draw some

play03:59

comparison

play04:00

to pandas which had the original Json

play04:02

normalized function so let's also in

play04:05

this next cell let's actually open up a

play04:07

new cell here and type import pandas as

play04:11

PD oops there we go import pandas as PD

play04:16

and then we're going to do the exact

play04:18

same thing so I can actually just copy

play04:20

and

play04:20

paste well actually probably both of

play04:23

these lines here put them in down here

play04:26

and now the function is a little bit

play04:28

different the pandas function does not

play04:30

have a strict parameter and we don't

play04:33

need to worry about that in pandas

play04:34

because it doesn't worry about mixed

play04:36

data type so we're going to go ahead now

play04:38

that we have this and actually we need

play04:40

to change this guy here to PD and then

play04:44

we're going to run the

play04:48

cell okay so we have the exact same data

play04:52

frame essentially there are some visual

play04:54

differences here you can see we've got

play04:55

the actual data type on the Polar side

play04:58

we do have this information

play05:00

as well in pandas but it's just not

play05:02

displayed visually in the actual data

play05:04

frame as you can

play05:05

tell so in both of these you should

play05:08

notice that most columns contain long

play05:10

names with items separated by periods

play05:13

this is a result of flattening the Json

play05:15

structure and what you're seeing are

play05:18

essentially the paths to each of these

play05:20

values that it's grabbed here so in this

play05:23

case you know we can see Meta do. ID

play05:27

that is the path that led us to this

play05:29

flat structure that gave us this value

play05:31

and you'll also notice that there are

play05:33

some values that contain nested items

play05:37

and this is because both functions only

play05:39

normalize the key value pairs if a value

play05:43

is an array or a list then it's placed

play05:45

into the data frame as a list so you'll

play05:48

see that here in both

play05:50

instances we can access these values and

play05:53

even create separate data frames based

play05:55

on the contents in pandas you simply

play05:58

need to use the record path argument and

play06:01

so let's demonstrate that now so down

play06:03

here in this next section we're going to

play06:06

demonstrate that and we're actually

play06:09

going to go ahead and copy the same data

play06:12

as before just to make it a little bit

play06:14

easier and then what we're going to do

play06:16

now is pass the record path variable

play06:19

excuse me record path parameter and then

play06:22

we're going to pass a list that's going

play06:25

to walk us to the path that we're

play06:27

seeking so let's take for example

play06:29

example there is a meta column so we're

play06:33

going to type

play06:35

meta and we're going to get the column

play06:37

names out of this path that we're typing

play06:38

here so we're going to type meta View

play06:42

and then

play06:44

columns okay now that we have this we

play06:47

can go ahead and run

play06:49

it so now we essentially have a new data

play06:52

frame based on the record path that we

play06:54

passed and like I was mentioning before

play06:56

this was previously a list with some

play06:58

nested information which we've basically

play07:01

unpacked now with this record path

play07:04

argument we can get the same information

play07:06

in polers but we don't have a record

play07:09

path argument instead we'll need to

play07:11

index the object directly so let's go

play07:14

ahead and we're going to grab our

play07:16

example from

play07:18

polers bring that back down

play07:22

here and so in this case we're going to

play07:25

actually just index off of here so we're

play07:27

going to say meta

play07:30

then we got to keep indexing so we'll

play07:31

say

play07:33

view some more straight brackets and

play07:37

then

play07:38

columns okay now if we run this we

play07:43

should get the exact same data frame

play07:45

which you can see in the output we do

play07:47

have the exact same

play07:48

information so we've created a new data

play07:51

frame for column headers but what about

play07:53

the actual data if you recall we found

play07:56

this information in the First Column

play07:58

let's try packing that now we'll do the

play08:01

exact same thing as before this time

play08:03

we're going to pass data as the record

play08:05

path so let's go ahead and show it for

play08:07

both pandas and polers I'm going to just

play08:09

copy and paste and then I'm going to

play08:12

change this to

play08:14

data and let's go ahead and run

play08:17

this and now we get our data neatly

play08:20

displayed you'll notice that column

play08:22

headers are missing and we could

play08:24

potentially add them in based on the

play08:26

column headers data frame we got earlier

play08:28

but let's demonstrate how to do this

play08:30

same exact thing in polers so I'm going

play08:33

to go ahead and scroll back up here

play08:36

going to copy our polar

play08:38

example and so I'm going to Index this

play08:41

time off of the data once again and

play08:46

let's go ahead and run

play08:48

this and in the output we get a weird

play08:51

mess now I actually spoke with the polar

play08:53

developers on this and they said it was

play08:55

because of the mixed data types that are

play08:57

happening in this portion of the file at

play08:59

the time of this recording the function

play09:01

is very new so perhaps some changes will

play09:04

be made to remedy this but they did give

play09:06

me a solution that appears to work just

play09:08

fine and we're going to walk through

play09:09

that now so we're going to come into

play09:12

this next cell and we're going to type

play09:14

DF set it equal to pl.

play09:19

dataframe and then we're going to pass

play09:22

our index data once more so we're going

play09:24

to say

play09:24

data and then pass the data index and

play09:28

you'll notice that we're not even using

play09:30

the Json normalized function right now

play09:32

um but bear with me here we're going to

play09:33

kind of demonstrate how it works a

play09:35

little bit more we're going to say

play09:37

Orient and then we're going to say we

play09:41

want to orient it in a row

play09:44

fashion okay so I'm going to call DF and

play09:47

do the first five rows by typing the

play09:49

head method and let's go ahead and run

play09:52

that and now you can see that we

play09:54

actually have the data that we were

play09:55

looking for and so definitely a little

play09:59

bit weird a little bit different um

play10:01

again I I hope that maybe some changes

play10:03

are made to the Json normalized function

play10:05

that will maybe help with some of those

play10:07

weird situations that we ran into um but

play10:10

it works and that's the important part

play10:12

here and now you know how to do

play10:14

it with that we'll end the video here if

play10:18

you have any questions or comments

play10:19

please feel free to drop them in the

play10:21

chat and we'll catch up with you at the

play10:22

next one

Rate This

5.0 / 5 (0 votes)

関連タグ
Json NormalizePolarsDonnées imbriquéesPandasPythonTabulaireDataframeConversion JsonAPI JsonData Science
英語で要約が必要ですか?