How to use json_normalize in Polars
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
📊 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.
🔍 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.
🛠 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
💡Json normalize
💡Version 1.0
💡Python dictionary
💡Tabular format
💡Nested Json data
💡Strict parameter
💡Pandas
💡Record path
💡Dataframe
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
welcome back in this video we're going
to show you how to use the polar's Json
normalized function now this function
was released in polar's version 1.0 so
if you don't have that version or a more
recent version installed on your
computer you'll definitely need to
upgrade that first in order to use it
with that said let's give a brief
introduction into what Json normalize
does and how it's different from other
Json functions you might see in polers
Json normalize is not technically
considered an IO function that's because
you are not directly reading Json data
into a data frame when you use it
instead you first need to read your Json
file or Json string into a python
dictionary using the built-in Json
library that said I unofficially
consider Json normalize an input
function because you utilize it almost
immediately after the data is read into
python now the primary purpose of Json
normalize is to transform Jason data by
flattening it into a tabular format this
comes in handy in a number of
circumstances including when you need to
read local non-normalized Json files or
when receiving nested Json data from an
API you'll notice that I use
non-normalized and nested
interchangeably you can also utilize
normalized and flat interchangeably when
your Json data is in a flat non- nested
format you can use other functions like
read Json
and scan Json but these functions are
absolutely useless if your data is not
normalized with that said let's dive
into implementing the Json normalized
function okay so we're going to start by
importing
Json and we got to import
polers as
PL and I'm actually going to go ahead
and just run
that so now we have our libraryi in here
and and that'll now enable us to get
some help when we're kind of typing out
some of these
functions uh Next Step we're going to
import our data so we have this electric
vehicles Json file that we're going to
use I won't open it because it's rather
large and it might take a lot of memory
so we're going to go ahead now and just
upload that or load that into python
dictionary so we're going to say f is
equal to
open and then we're going to type the
path to our data set and one thing that
you can do is just drag it and then hold
the shift key and that should put it in
there do need to close it in some quotes
there and then the last thing I'm going
to do is just make it so that we are
reading this file using that R uh
character there okay next step I'm going
to type data and set it equal to
json. load and so this is where we're
going to load our Json file make it a
python
dictionary and that is how we're going
to get that initial dictionary in and
then we're going to go ahead and import
or excuse me we're going to go ahead and
now use the function so we're going to
type
pl. Json
normalize and then we just need to pass
our data in
here and so by default polers is going
to be strict about how it constructs the
data frame meaning that it won't allow
for mixed data types and I already know
that this data that we're working with
has some mixed data types so I'm going
to go ahead and set another parameter in
here that is the strict parameter I'm
going to set that equal to
false and we're going to go ahead and
address the mixed data types A little
bit later let's go ahead and display our
data here I'm going to go ahead and type
DF and then just select the top five by
typing the head
method and when we run
that we get a new data frame that's been
flattened now I want to draw some
comparison
to pandas which had the original Json
normalized function so let's also in
this next cell let's actually open up a
new cell here and type import pandas as
PD oops there we go import pandas as PD
and then we're going to do the exact
same thing so I can actually just copy
and
paste well actually probably both of
these lines here put them in down here
and now the function is a little bit
different the pandas function does not
have a strict parameter and we don't
need to worry about that in pandas
because it doesn't worry about mixed
data type so we're going to go ahead now
that we have this and actually we need
to change this guy here to PD and then
we're going to run the
cell okay so we have the exact same data
frame essentially there are some visual
differences here you can see we've got
the actual data type on the Polar side
we do have this information
as well in pandas but it's just not
displayed visually in the actual data
frame as you can
tell so in both of these you should
notice that most columns contain long
names with items separated by periods
this is a result of flattening the Json
structure and what you're seeing are
essentially the paths to each of these
values that it's grabbed here so in this
case you know we can see Meta do. ID
that is the path that led us to this
flat structure that gave us this value
and you'll also notice that there are
some values that contain nested items
and this is because both functions only
normalize the key value pairs if a value
is an array or a list then it's placed
into the data frame as a list so you'll
see that here in both
instances we can access these values and
even create separate data frames based
on the contents in pandas you simply
need to use the record path argument and
so let's demonstrate that now so down
here in this next section we're going to
demonstrate that and we're actually
going to go ahead and copy the same data
as before just to make it a little bit
easier and then what we're going to do
now is pass the record path variable
excuse me record path parameter and then
we're going to pass a list that's going
to walk us to the path that we're
seeking so let's take for example
example there is a meta column so we're
going to type
meta and we're going to get the column
names out of this path that we're typing
here so we're going to type meta View
and then
columns okay now that we have this we
can go ahead and run
it so now we essentially have a new data
frame based on the record path that we
passed and like I was mentioning before
this was previously a list with some
nested information which we've basically
unpacked now with this record path
argument we can get the same information
in polers but we don't have a record
path argument instead we'll need to
index the object directly so let's go
ahead and we're going to grab our
example from
polers bring that back down
here and so in this case we're going to
actually just index off of here so we're
going to say meta
then we got to keep indexing so we'll
say
view some more straight brackets and
then
columns okay now if we run this we
should get the exact same data frame
which you can see in the output we do
have the exact same
information so we've created a new data
frame for column headers but what about
the actual data if you recall we found
this information in the First Column
let's try packing that now we'll do the
exact same thing as before this time
we're going to pass data as the record
path so let's go ahead and show it for
both pandas and polers I'm going to just
copy and paste and then I'm going to
change this to
data and let's go ahead and run
this and now we get our data neatly
displayed you'll notice that column
headers are missing and we could
potentially add them in based on the
column headers data frame we got earlier
but let's demonstrate how to do this
same exact thing in polers so I'm going
to go ahead and scroll back up here
going to copy our polar
example and so I'm going to Index this
time off of the data once again and
let's go ahead and run
this and in the output we get a weird
mess now I actually spoke with the polar
developers on this and they said it was
because of the mixed data types that are
happening in this portion of the file at
the time of this recording the function
is very new so perhaps some changes will
be made to remedy this but they did give
me a solution that appears to work just
fine and we're going to walk through
that now so we're going to come into
this next cell and we're going to type
DF set it equal to pl.
dataframe and then we're going to pass
our index data once more so we're going
to say
data and then pass the data index and
you'll notice that we're not even using
the Json normalized function right now
um but bear with me here we're going to
kind of demonstrate how it works a
little bit more we're going to say
Orient and then we're going to say we
want to orient it in a row
fashion okay so I'm going to call DF and
do the first five rows by typing the
head method and let's go ahead and run
that and now you can see that we
actually have the data that we were
looking for and so definitely a little
bit weird a little bit different um
again I I hope that maybe some changes
are made to the Json normalized function
that will maybe help with some of those
weird situations that we ran into um but
it works and that's the important part
here and now you know how to do
it with that we'll end the video here if
you have any questions or comments
please feel free to drop them in the
chat and we'll catch up with you at the
next one
تصفح المزيد من مقاطع الفيديو ذات الصلة
Build a Simple Notion Second Brain from Scratch (in ONLY 10 Minutes)
Notre gestion des déchets ménagers
ChatGPT : La Formation Ultime | Tutoriel Ultra Complet pour Débutants
Langage SQL - Vidéo 5: SELECT / DISTINCT / WHERE
Cette IA transforme ton Excel en application en 5 min ! BLUFFANT !
Excel - corrigé - Fonctions statistiques Decathlon
5.0 / 5 (0 votes)