Preparation
Before any data manipulation can occur, two (2) new libraries will require installation.
- The Pandas library enables access to/from a DataFrame.
- The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.
To install these libraries, navigate to an IDE terminal. At the command prompt ($
), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($
). Your terminal prompt may be different.
$ pip install pandas
Hit the <Enter> key on the keyboard to start the installation process.
$ pip install numpy
Hit the <Enter> key on the keyboard to start the installation process.
If the installations were successful, a message displays in the terminal indicating the same.
Feel free to view the PyCharm installation guide for the required libraries.
Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.
import pandas as pd import numpy as np
DataFrame.from_dict()
The from_dict()
classmethod converts a valid dictionary structure into a DataFrame format. Upon conversion, the keys of the original dictionary translate to DataFrame columns.
The syntax for this method is as follows:
classmethod DataFrame.from_dict(data, orient='columns', dtype=None, columns=None)
Parameter | Description |
---|---|
data | The parameter is a valid dictionary to be converted. |
orient | The available options are: – 'columns' : if keys are columns, pass this option. Selected by default.– 'index' : If keys are rows, pass this option.– 'tight' : if tight, assume a dictionary with keys. |
dtype | This parameter is the data type to force. Otherwise, it is, by default, infer . |
columns | This parameter is the column(s) to use if orient is 'index' . |
For this example, a Dictionary containing the first five (5) elements of the Periodic Table convert to a DataFrame.
elements = {'Hydrogen': [1, 1766], 'Helium': [2, 1868], 'Lithium': [3, 1817], 'Beryllium': [4, 1798], 'Boron': [5, 1808]} periodic_df = pd.DataFrame.from_dict(elements, orient='index', columns=['Atomic #', 'Discovered']) print(periodic_df)
- Line [1] creates a dictionary of lists and saves it to the variable elements.
- Line [2] does the following:
- creates a DataFrame from the elements Dictionary
- sets the orient parameter to index
- sets the column names to clearly identify the data
- saves the output to the
periodic_df
DataFrame
- Line [3] outputs the DataFrame to the terminal.
Output
Atomic # | Discovered | |
Hydrogen | 1 | 1766 |
Helium | 2 | 1868 |
Lithium | 3 | 1817 |
Beryllium | 4 | 1798 |
Boron | 5 | 1808 |
More Pandas DataFrame Methods
Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:
Also, check out the full cheat sheet overview of all Pandas DataFrame methods.