To generate random numbers in a pandas DataFrame or Series, you use NumPy’s random module—pandas itself has no built-in random generator. The core function is numpy.random.default_rng(), which creates a random number generator (RNG) you can then call methods like .integers(), .uniform(), or .normal() on. This guide shows you four practical ways to add random numbers to your data, from a single column to an entire DataFrame, with full control over distribution and reproducibility.
What You’ll Need
- Python 3.7 or later.
- pandas installed (e.g.,
pip install pandas). - NumPy installed (comes with pandas automatically).
- Your data already in a DataFrame or Series, or you can create one from scratch.
Step-by-Step
Method 1: Create a Series of Random Integers
- Import the libraries. At the top of your script, write:
import pandas as pd import numpy as np - Create a random number generator. The recommended way is:
rng = np.random.default_rng()This gives you a modern generator with better statistical properties than the older
np.random.randint(). - Generate integers. Use
rng.integers(low, high, size). For example, 10 random integers between 1 and 100 (inclusive of 1, exclusive of 100):random_ints = rng.integers(1, 100, size=10) print(random_ints)Output will be an array like:
[42 17 83 56 91 24 68 35 79 10](your values will differ). - Convert to a pandas Series. Simply pass the array to
pd.Series():series = pd.Series(random_ints, name='random_integers') print(series)
Method 2: Add a Random Column to an Existing DataFrame
- Assume you have a DataFrame like this:
df = pd.DataFrame({'id': range(1, 6)}) - Create a generator and add a column with random floats between 0 and 1:
rng = np.random.default_rng() df['random_float'] = rng.random(size=len(df)) print(df)The
rng.random()method returns values in [0.0, 1.0). Thesizemust match the number of rows. - To add integers instead, use
rng.integers()with the same size:df['random_int'] = rng.integers(0, 100, size=len(df))
Method 3: Generate an Entire DataFrame of Random Numbers
- Decide the shape. For a 5-row, 3-column DataFrame of random floats:
rng = np.random.default_rng() data = rng.random(size=(5, 3)) df_random = pd.DataFrame(data, columns=['A', 'B', 'C']) print(df_random) - For integers, use
rng.integers()with a tuple for size:data_int = rng.integers(1, 10, size=(5, 3)) df_int = pd.DataFrame(data_int, columns=['X', 'Y', 'Z'])
Method 4: Use Specific Distributions (Normal, Uniform, etc.)
- Normal distribution. To get values from a normal (Gaussian) distribution with mean 0 and standard deviation 1:
rng = np.random.default_rng() df['normal'] = rng.normal(loc=0, scale=1, size=len(df)) - Uniform distribution. For uniform values between 10 and 20:
df['uniform'] = rng.uniform(low=10, high=20, size=len(df)) - Other distributions include
rng.binomial(),rng.poisson(),rng.exponential(), etc. Check NumPy documentation for the full list.
Setting a Seed for Reproducibility
- Pass an integer to
default_rng()to make the random sequence repeatable:rng = np.random.default_rng(42) print(rng.random(3)) # same every time you run with seed 42 - Use the same seed in different runs to get identical results, which is crucial for testing or sharing code.
Common Mistakes
- Using
np.random.seed()withdefault_rng(). The old-stylenp.random.seed(42)does not affectdefault_rng(). Usenp.random.default_rng(42)instead. - Ignoring the
sizeparameter. If you forgetsize=len(df), you might get a single number instead of a column, or a shape mismatch error. - Using
random.random()from Python’s built-in module. That works but is slower and less flexible for arrays. Stick with NumPy. - Confusing
randintwithintegers. The oldnp.random.randintis deprecated; userng.integers(). - Not checking the upper bound.
rng.integers(1, 100)gives numbers from 1 to 99 inclusive. If you want 100, userng.integers(1, 101).
Tips
- Use
default_rng()over legacy functions. It’s faster and has a better random number algorithm. - For large datasets, generate all numbers at once with a single
sizecall rather than looping—it’s much faster. - Name your columns descriptively to avoid confusion later.
- If you need to reproduce results, always set a seed at the top of your script.
- Check the distribution with
df.describe()or a histogram to ensure it looks as expected. - For integers, remember that the high value is exclusive—adjust accordingly.
Troubleshooting
- Error: ‘numpy’ has no attribute ‘random’ — You may have an old NumPy version. Update with
pip install --upgrade numpy. - Error: Length of values does not match length of index — Your
sizedoes not match the DataFrame length. Usesize=len(df). - Error: ‘Generator’ object has no attribute ‘randint’ — The
Generatorobject usesintegers(), notrandint(). Change it. - Getting the same numbers every time without setting a seed? That’s not possible unless you set a seed. If you see repetition, check if you accidentally set a seed earlier.
- Random numbers look too clustered? That’s normal for small samples. Increase the sample size or use a different distribution.
Frequently Asked Questions
Can I generate random numbers directly in pandas without NumPy?
No, pandas relies on NumPy for random number generation. You always need to import numpy and use its random module.
How do I generate random dates in pandas?
Generate random integers representing day offsets and add them to a start date. For example: start = pd.Timestamp('2023-01-01'); offsets = rng.integers(0, 365, size=10); dates = start + pd.to_timedelta(offsets, unit='D').
What is the difference between np.random.rand() and rng.random()?
Both produce uniform floats in [0,1). np.random.rand() is from the legacy global random state, while rng.random() is from a modern Generator and is preferred for new code.
How can I make random numbers reproducible across runs?
Create the generator with a seed: rng = np.random.default_rng(42). Use that same seed every time you run the script.
Can I generate random strings in pandas?
Yes, but it’s not built-in. You can use np.random.choice to pick from a list of characters, or use Python’s random.choices and apply it row-wise. For example: import random; df['rand_str'] = [''.join(random.choices('abc', k=3)) for _ in range(len(df))].
Why use default_rng() instead of np.random.seed()?
default_rng() creates a separate generator object, avoiding global state issues and giving better performance and statistical quality. It’s the recommended approach in modern NumPy.
Related
- Is Data Entry Hard? Honest Answer
- How to Generate Random Numbers in RStudio
- Data Entry Role in SAM.gov: What It Really Means
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- PowerPoint: How to Animate Part of TextYes. PowerPoint can reveal text by paragraph, word, or letter, but if you want one specific phrase to…
- VLOOKUP Did Not Find Value in Google Sheets?If VLOOKUP did not find a value in Google Sheets, the usual cause is that the lookup key…
- Proper Excel Table Setup: A Clear Step-by-Step GuideTo set up an Excel table, arrange one record per row and one field per column, give every…
- Present PowerPoint Without Showing NotesYes. PowerPoint normally keeps speaker notes off the audience’s slide show; to make sure they stay private, present…
- Excel Scatter Plot Line of Best Fit: Add and InterpretTo add a line of best fit in Excel for Microsoft 365 on Windows, select your scatter plot,…
- Google Sheets: Remove Dropdown from CellTo remove a dropdown from a cell in Google Sheets, select the cell (or range), go to Data…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.