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_records()
The from_records()
classmethod converts a valid ndarray
, tuple, or dictionary structure into a DataFrame format.
The syntax for this method is as follows:
classmethod DataFrame.from_records(data, index=None, exclude=None, columns=None, coerce_float=False, nrows=None)
Parameter | Description |
---|---|
data | This parameter is a valid ndarray , tuple, or dictionary structure. |
index | A field of arrays for the index or a list containing a specific set. |
exclude | The columns/fields to exclude from the conversion. |
columns | The column names to use in the conversion. |
coerce_float | This parameter tries to convert decimal values to floats. |
nrows | If an iterator, the number of rows to read in. |
This example converts a list of tuples (an ndarray
) containing four (4) fictitious Finxter users to a DataFrame.
data = np.array([(30022145, 'wildone92'), (30022192, 'AmyP'), (30022331, '1998_pete'), (30022345, 'RexTex')]) users_df = pd.DataFrame.from_records(data, columns=['ID', 'Username']) print(users_df)
- Line [1] creates a list of tuples (ndarray) and saves it to the
data
variable. - Line [2] does the following:
- creates a DataFrame from the
data
variable - sets the column names to clearly identify the data
- creates a DataFrame from the
- Outputs the DataFrame to the terminal.
Output
ID | Username | |
0 | 30022145 | wildone92 |
1 | 30022192 | AmyP |
2 | 30022331 | 1998_pete |
3 | 30022345 | RexTex |
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.