Come convertire un file json in un pandas dataframe
A volte potresti voler convertire un file JSON in un DataFrame panda. Fortunatamente, questo è facile da fare utilizzando la funzione read_json() di panda, che utilizza la seguente sintassi:
read_json(‘percorso’, orientamento=’indice’)
Oro:
- percorso: il percorso del tuo file JSON.
- orient: l’orientamento del file JSON. Il valore predefinito è “indice”, ma è possibile specificare invece “divisione”, “record”, “colonne” o “valori”.
Gli esempi seguenti mostrano come utilizzare questa funzione per una varietà di stringhe JSON diverse.
Esempio 1: conversione di un file JSON con un formato “Record”.
Supponiamo di avere un file JSON chiamato my_file.json nel seguente formato:
[
{
"points": 25,
“assists”: 5
},
{
"points": 12,
“assists”: 7
},
{
"points": 15,
“assists”: 7
},
{
"points": 19,
“assists”: 12
}
]
Possiamo caricare questo file JSON in un DataFrame panda semplicemente specificando il percorso con orient=’ records ‘ come segue:
#load JSON file into pandas DataFrame df = pd. read_json ('C:/Users/Zach/Desktop/json_file.json', orient=' records ') #view DataFrame df assist points 0 5 25 1 7 12 2 7 15 3 12 19
Esempio 2: conversione di un file JSON con un formato “Indice”.
Supponiamo di avere un file JSON chiamato my_file.json nel seguente formato:
{
"0": {
"points": 25,
“assists”: 5
},
"1": {
"points": 12,
“assists”: 7
},
"2": {
"points": 15,
“assists”: 7
},
"3": {
"points": 19,
“assists”: 12
}
}
Possiamo caricare questo file JSON in un DataFrame panda semplicemente specificando il percorso con orient=’ index ‘ come segue:
#load JSON file into pandas DataFrame df = pd. read_json ('C:/Users/Zach/Desktop/json_file.json', orient=' index ') #view DataFrame df assist points 0 5 25 1 7 12 2 7 15 3 12 19
Esempio 3: conversione di un file JSON con un formato “Colonne”.
Supponiamo di avere un file JSON chiamato my_file.json nel seguente formato:
{
"dots": {
"0": 25,
"1": 12,
"2": 15,
"3": 19
},
"assists": {
"0": 5,
"1": 7,
"2": 7,
"3": 12
}
}
Possiamo caricare questo file JSON in un DataFrame panda semplicemente specificando il percorso con orient=’ columns ‘ come segue:
#load JSON file into pandas DataFrame df = pd. read_json ('C:/Users/Zach/Desktop/json_file.json', orient=' columns ') #view DataFrame df assist points 0 5 25 1 7 12 2 7 15 3 12 19
Esempio 4: conversione di un file JSON con un formato “Values”.
Supponiamo di avere un file JSON chiamato my_file.json nel seguente formato:
[
[
25,
5
],
[
12,
7
],
[
15,
7
],
[
19,
12
]
]
Possiamo caricare questo file JSON in un DataFrame panda semplicemente specificando il percorso con orient=’ values ‘ come segue:
#load JSON file into pandas DataFrame df = pd. read_json ('C:/Users/Zach/Desktop/json_file.json', orient=' values ') #view DataFrame df 0 1 0 25 5 1 12 7 2 15 7 3 19 12 3 12 19
Puoi trovare la documentazione completa della funzione read_json() qui .
Risorse addizionali
Come leggere file Excel con Panda
Come leggere file CSV con Pandas