Pandas DataFrame sample() Method

Rate this post

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 sample()

The sample() method retrieves and returns a random sample of columns or rows (depending on the selected axis) from a DataFrame/Series.

The syntax for this method is as follows:

DataFrame.sample(n=None, frac=None, replace=False, weights=None, 
                 random_state=None, axis=None, ignore_index=False)
ParameterDescription
nN is the number of elements (items) to return from the selected axis. By default, one (1).
fracThe fraction of elements (items) to return from the selected axis. If frac, do not use the N parameter. If the value of frac is more than one (1) replace parameter must be True.
replaceIf True, allow a sample of the same row more than once. If False, do not allow the same row more than once. By default, False.
weightsIf None, weight is set to equal probability weighting. If a Series, it will align with the object on the index. If not located, ignore the index: assign the weights zero (0). If a DataFrame, accept the column name when the selected axis is zero (0).
axisIf zero (0) or index is selected, apply to each column. Default 0.
If one (1) apply to each row.
ignore_indexIf True, the index will start numbering from 0 on (ex: 0, 1, 2, etc.).

For these examples, the finxters.csv data saves to a DataFrame to manipulate the data.

df = pd.read_csv('finxters.csv')
result = df['First_Name'].sample(n=3, random_state=1)
print(result)
  • Line [1] reads in the comma-separated CSV file and saves it to df.
  • Line [2] retrieves three (3) random ‘First_Names‘ values and saves them to the result variable.
  • Line [3] outputs the result to the terminal.

Output

27Victoria
35Diana
40Owen
Name: First_Name, dtype: object

In this example, the np.random.randint() method calls and generates random integers on a selected column.

Code – Example 2

df   = pd.read_csv('finxters.csv')
nums = np.random.randint(df['FID'], size=50)
result = df['FID'].sample(n=3, random_state=nums)
print(result)
  • Line [1] reads in the comma-separated CSV file and saves it to df.
  • Line [2] generates random integers (np.random.randint()) from the CSV file based on the ‘FID‘ column.
  • Line [3] retrieves three (3) integers from the random numbers generated on Line [2]. This output saves to the result variable.
  • Line [4] outputs the result to the terminal.

Output

343002381
153002244
173002260
Name: FID, dtype: int64

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.