API · Pandas
Pandas DataFrame.to_dict() Funktion
Die Funktion DataFrame to_dict() konvertiert den angegebenen DataFrame in ein Dictionary.
Auf dieser Seite
Die Python-Pandas-Funktion DataFrame.to_dict() konvertiert den angegebenen DataFrame in ein Dictionary.
Syntax von pandas.DataFrame.to_dict():
DataFrame.to_dict(orient='dict',
into= < class 'dict' >)
Parameter
orient |
Dieser Parameter bestimmt den Typ des Dictionaries. Es kann zum Beispiel ein Serien- oder Listen-Dictionary sein. Er hat sechs Optionen. Diese sind dict, list, Series, split, records, und index. |
into |
Dies ist ein Klassenparameter. Wir können eine aktuelle Klasse oder ihre Instanz als Parameter übergeben. |
Zurück
Gibt das Dictionary zurück, das den übergebenen DataFrame darstellt.
Beispielcodes: Methode DataFrame.to_dict() zum Konvertieren des DataFrames in ein Dictionary von Wörterbüchern
Um einen DataFrame in ein Dictionary von Wörterbüchern zu konvertieren, übergeben wir keine Parameter.
import pandas as pd
dataframe=pd.DataFrame({'Attendance': {0: 60, 1: 100, 2: 80,3: 78,4: 95},
'Name': {0: 'Olivia', 1: 'John', 2: 'Laura',3: 'Ben',4: 'Kevin'},
'Obtained Marks': {0: 90, 1: 75, 2: 82, 3: 64, 4: 45}})
print("The Original Data frame is: \n")
print(dataframe)
dataframe1 = dataframe.to_dict()
print("The Dictionary of Dictionaries is: \n")
print(dataframe1)
Ausgabe:
The Original Data frame is:
Attendance Name Obtained Marks
0 60 Olivia 90
1 100 John 75
2 80 Laura 82
3 78 Ben 64
4 95 Kevin 45
The Dictionary of Dictionaries is:
{'Attendance': {0: 60, 1: 100, 2: 80, 3: 78, 4: 95}, 'Obtained Marks': {0: 90, 1: 75, 2: 82, 3: 64, 4: 45}, 'Name': {0: 'Olivia', 1: 'John', 2: 'Laura', 3: 'Ben', 4: 'Kevin'}}
Die Funktion hat das Dictionary der Wörterbücher zurückgegeben.
Beispiel-Codes: DataFrame.to_dict() Methode zur Konvertierung eines DataFrames in ein Dictionary von Reihen
Um einen DataFrame in ein Dictionary von Serien zu konvertieren, übergeben wir Series als orient Parameter.
import pandas as pd
dataframe=pd.DataFrame({'Attendance': {0: 60, 1: 100, 2: 80,3: 78,4: 95},
'Name': {0: 'Olivia', 1: 'John', 2: 'Laura',3: 'Ben',4: 'Kevin'},
'Obtained Marks': {0: 90, 1: 75, 2: 82, 3: 64, 4: 45}})
print("The Original Data frame is: \n")
print(dataframe)
dataframe1 = dataframe.to_dict('series')
print("The Dictionary of Series is: \n")
print(dataframe1)
Ausgabe:
The Original Data frame is:
Attendance Name Obtained Marks
0 60 Olivia 90
1 100 John 75
2 80 Laura 82
3 78 Ben 64
4 95 Kevin 45
The Dictionary of Series is:
{'Attendance': 0 60
1 100
2 80
3 78
4 95
Name: Attendance, dtype: int64, 'Obtained Marks': 0 90
1 75
2 82
3 64
4 45
Name: Obtained Marks, dtype: int64, 'Name': 0 Olivia
1 John
2 Laura
3 Ben
4 Kevin
Name: Name, dtype: object}
Die Funktion hat das Dictionary der Reihen zurückgegeben.