Generating Random Integers in Pandas Dataframe

Generating Random Integers in Pandas Dataframe

Creating a Pandas DataFrame with random integers can be done using the numpy library in conjunction with Pandas. Here's how you can generate a DataFrame with random integers:

import pandas as pd import numpy as np # Define the size of the DataFrame rows = 10 # Number of rows cols = 5 # Number of columns # Define the range of the random numbers min_value = 1 max_value = 100 # Create a DataFrame with random integers between min_value and max_value df = pd.DataFrame(np.random.randint(min_value, max_value+1, size=(rows, cols)), columns=[f'Column_{i}' for i in range(1, cols+1)]) print(df) 

In this script:

  • rows and cols are the number of rows and columns for the DataFrame.
  • min_value and max_value define the range for the random integers.
  • np.random.randint is used to generate a 2D array of random integers between min_value and max_value inclusive.
  • The resulting array is passed to the Pandas DataFrame constructor to create the DataFrame.
  • columns=[f'Column_{i}' for i in range(1, cols+1)] creates a list of column names dynamically based on the number of columns.

When you run this code, you'll get a DataFrame of the specified size filled with random integers in the given range.


More Tags

device-manager datetimeoffset remote-host lapply blue-screen-of-death ms-word matplotlib-basemap mtu rows appendchild

More Programming Guides

Other Guides

More Programming Examples