Convert Pandas DataFrame to Dictionary
This tutorial will show you how to convert a Pandas DataFrame into a dictionary with the index column elements as keys and the corresponding elements of other columns as values. We will use the following DataFrame in the article.
import pandas as pd
df = pd.DataFrame(
[["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
columns=["Name", "Age", "Course"],
)
print(df)
Output:
Name Age Course
0 Jay 16 BBA
1 Jack 19 BTech
2 Mark 18 BSc
to_dict()
Convert a Pandas DataFrame to a dictionary using the
The Pandas to_dict()
function converts a DataFrame to a dictionary. The parameters determine the format of the dictionary and how the key-value pairs are associated. Below is a to_dict()
basic example of using convertDataFrame to Dictionary.
import pandas as pd
df = pd.DataFrame(
[["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
columns=["Name", "Age", "Course"],
)
d1 = df.to_dict()
print(d1)
Output:
{'Name': {0: 'Jay', 1: 'Jack', 2: 'Mark'}, 'Age': {0: 16, 1: 19, 2: 18}, 'Course': {0: 'BBA', 1: 'BTech', 2: 'BSc'}}
As you can see in the output, the column names are converted to keys, each record as value and the index as their key.
Pandas DataFrame Methods for Converting Dictionaries
We can change the format of the final dictionary by passing arguments list
, records
, series
, index
, split
and . For example, when we pass and as arguments, we get the column names as keys, but the value pairs are converted to lists and series rows, respectively. The following example will demonstrate this.dict
list
series
import pandas as pd
df = pd.DataFrame(
[["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
columns=["Name", "Age", "Course"],
)
d_list = df.to_dict("list")
print(d_list)
d_series = df.to_dict("series")
print(d_series)
Output:
{'Name': ['Jay', 'Jack', 'Mark'], 'Age': [16, 19, 18], 'Course': ['BBA', 'BTech', 'BSc']}
{'Name': 0 Jay
1 Jack
2 Mark
Name: Name, dtype: object, 'Age': 0 16
1 19
2 18
Name: Age, dtype: int64, 'Course': 0 BBA
1 BTech
2 BSc
Name: Course, dtype: object}
Pandas DataFrame to List of Dictionaries
We can also pass each line as a separate dictionary to the function records
. The final result is a list with each line as a dictionary. For example:
import pandas as pd
df = pd.DataFrame(
[["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
columns=["Name", "Age", "Course"],
)
d_records = df.to_dict("records")
print(d_records)
Output:
[{'Name': 'Jay', 'Age': 16, 'Course': 'BBA'}, {'Name': 'Jack', 'Age': 19, 'Course': 'BTech'}, {'Name': 'Mark', 'Age': 18, 'Course': 'BSc'}]
Pandas DataFrame to Dictionary by Row
But in many cases, we may not want the column names as dictionary keys. For such cases, we can pass index
DataFrame index as key. The following code snippet demonstrates this.
import pandas as pd
df = pd.DataFrame(
[["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
columns=["Name", "Age", "Course"],
)
d_index = df.to_dict("index")
print(d_index)
Output:
{0: {'Name': 'Jay', 'Age': 16, 'Course': 'BBA'}, 1: {'Name': 'Jack', 'Age': 19, 'Course': 'BTech'}, 2: {'Name': 'Mark', 'Age': 18, 'Course': 'BSc'}}
Dataframe converted to a dictionary with one column as key
But what if we prefer to use the elements of one column as keys and the elements of other columns as values? This can be achieved by simply taking the desired column as the index of the DataFrame and .T()
transposing it using the function.
example:
import pandas as pd
df = pd.DataFrame(
[["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
columns=["Name", "Age", "Course"],
)
d_names = df.set_index("Name").T.to_dict("list")
print(d_names)
Output:
{'Jay': [16, 'BBA'], 'Jack': [19, 'BTech'], 'Mark': [18, 'BSc']}
Convert a Pandas DataFrame to a dictionary using the dict()
and functionszip()
Python dict()
functions can also convert Pandas DataFrame to dictionary. We should also use zip()
the function, passing each column as its argument to create a parallel iterator. Then zip()
the function will yield all the values of a row in each iteration.
import pandas as pd
df = pd.DataFrame(
[["Jay", 16, "BBA"], ["Jack", 19, "BTech"], ["Mark", 18, "BSc"]],
columns=["Name", "Age", "Course"],
)
d = dict([(i, [a, b]) for i, a, b in zip(df["Name"], df["Age"], df["Course"])])
print(d)
Output:
{'Jay': [16, 'BBA'], 'Jack': [19, 'BTech'], 'Mark': [18, 'BSc']}
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
将 Pandas 转换为不带索引的 CSV
Publish Date:2024/04/21 Views:202 Category:Python
-
本教程演示了如何将 Pandas DataFrame 转换为没有索引的 CSV。
将 Pandas DataFrame 转换为字典
Publish Date:2024/04/21 Views:141 Category:Python
-
本教程演示了如何将 Pandas DataFrame 转换为字典。
将 Pandas DataFrame 列转换为列表
Publish Date:2024/04/21 Views:144 Category:Python
-
本文介绍了如何将 Pandas DataFrame 列转换为列表。
将 Pandas DataFrame 转换为 JSON
Publish Date:2024/04/21 Views:157 Category:Python
-
本教程演示了如何将 Pandas DataFrame 转换为 JSON 字符串。
将 Pandas DataFrame 写入 CSV
Publish Date:2024/04/21 Views:189 Category:Python
-
本教程介绍了我们如何使用 pandas.DataFrame.to_csv()函数将 DataFrame 写入 CSV 文件。
使用 Python 将 Pandas DataFrame 保存为 HTML
Publish Date:2024/04/21 Views:109 Category:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
将 Pandas DataFrame 转换为系列
Publish Date:2024/04/21 Views:129 Category:Python
-
本文演示了将 Pandas DataFrame 转换为系列的方法。
将 Pandas DataFrame 转换为 Spark DataFrame
Publish Date:2024/04/20 Views:190 Category:Python
-
本教程将讨论将 Pandas DataFrame 转换为 Spark DataFrame 的不同方法。
将 Pandas DataFrame 导出到 Excel 文件
Publish Date:2024/04/20 Views:215 Category:Python
-
本教程介绍了有关如何将 Pandas DataFrame 导出到 excel 文件的各种方法