![]() |
VOOZH | about |
In this article, we will explore different methods of creating a DataFrame from a dictionary of lists/arrays.
The pd.DataFrame() constructor is the most direct way to create a DataFrame from a dictionary of ndarrays/lists. Each dictionary key becomes a column name and its corresponding list or array becomes the column values.
Example: In this example, a DataFrame is created using a dictionary with "Category" and "Marks" columns.
Category Marks 0 Array 20 1 Stack 21 2 Queue 19
Explanation: The dictionary keys (Category, Marks) become DataFrame columns. Each list provides values for that column. Default integer indices are assigned automatically.
When multiple value lists/arrays are given in the dictionary, pd.DataFrame() can directly construct a DataFrame with multiple columns. This is useful when storing values for different groups or individuals.
Example: This example creates a DataFrame with "Category", "Student_1" and "Student_2" columns, then transposes the table for better row-wise analysis.
0 1 2 Category Array Stack Queue Student_1 20 21 19 Student_2 15 20 14
Explanation: Each dictionary key creates a column in the DataFrame. The transpose() method swaps rows and columns for better readability
The index parameter in pd.DataFrame() allows you to assign custom labels to rows instead of default integer indices. This makes the DataFrame more descriptive and user-friendly.
Example: This program creates a DataFrame with custom row indices "Cat_1", "Cat_2" and "Cat_3".
Area Student_1 Student_2 Cat_1 Array 20 15 Cat_2 Stack 21 20 Cat_3 Queue 19 14
Explanation: The index parameter sets custom row labels. Each key in the dictionary still corresponds to a column.