📜  pandas dataframe.to_dict - Python (1)

📅  最后修改于: 2023-12-03 15:33:23.521000             🧑  作者: Mango

Pandas DataFrame.to_dict - Python

Pandas is a powerful data manipulation tool used widely in the scientific and financial industries. One of its most powerful features is its ability to convert to and from dictionaries. The to_dict() method is used to convert a Pandas DataFrame to a dictionary.

Syntax
DataFrame.to_dict(self, orient='dict', into=<class 'dict'>)
Parameters
  • orient (optional): It determines the format of the dictionary to be returned.
    • dict (default): Returns the dictionary of the form {column -> {index -> value}}.
    • list: Returns the dictionary of the form {column -> [values]}.
    • series: Returns the dictionary of the form {column -> Series(values)}.
    • split: Returns the dictionary of the form {index -> {column -> value}}.
    • records: Returns the dictionary of the form [{column -> value}, … , {column -> value}].
    • index: Returns the dictionary of the form {keys -> {column -> value}}.
  • into (optional): It specifies the dictionary class to return. By default, it is dict.
Example
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'c']})

# convert dataframe to dictionary with default options
dict1 = df.to_dict()
print(dict1)

# convert dataframe to dictionary with orient='list'
dict2 = df.to_dict(orient='list')
print(dict2)

# convert dataframe to dictionary with orient='records'
dict3 = df.to_dict(orient='records')
print(dict3)

Output:

{'A': {0: 1, 1: 2, 2: 3}, 'B': {0: 'a', 1: 'b', 2: 'c'}}
{'A': [1, 2, 3], 'B': ['a', 'b', 'c']}
[{'A': 1, 'B': 'a'}, {'A': 2, 'B': 'b'}, {'A': 3, 'B': 'c'}]
Conclusion

The Pandas DataFrame.to_dict method is a powerful method that allows you to convert DataFrame objects to dictionary objects. With the ability to set the orientation of the conversion, this tool broadens its capability, providing a unified tool to transform data between formats and settings.