Skip to content
Related Articles

Related Articles

Generating Random Integers in Pandas Dataframe

View Discussion
Improve Article
Save Article
  • Last Updated : 10 Jul, 2020

Pandas is the most popular Python library that is used for data analysis. It provides highly optimized performance with back-end source code that is purely written in C or Python.

Here we will see how to generate random integers in the Pandas datagram. We will be using the numpy.random.randint() method to generate random integers.

Example 1 : Generating random integers in Pandas Single Data frame column.




# importing pandas and numpy libraries
import numpy as np
import pandas as pd
  
# generating 11 random integers from 5 to 35 
data = np.random.randint(5, 35, size = 11)
df = pd.DataFrame(data, columns = ['random_numbers'])
  
# displaying random integers in data frame
print(df)

Output :

Example 2 : Sorting a column in Pandas Single Data frame column.




# importing pandas and numpy libraries
import numpy as np
import pandas as pd
  
# generating 7 random integers from 5 to 35 
data = np.random.randint(5, 35, size = 7)
df = pd.DataFrame(data, columns = ['integers'])
  
# displaying random integers in data frame
print("Before Sorting :")
print(df)
  
# sorting the random integer values 
# using dataframe.sort_values()
# and displaying them 
df.sort_values("integers", axis = 0, ascending = True
                inplace = True, na_position ='last')
  
print("After Sorting :")
print(df)

Output :

Example 3 : Generating random integers in Pandas Multiple Data frame column.




# importing pandas and numpy libraries
import numpy as np
import pandas as pd
  
# generating 12X3 i.e 36 random integers from 5 to 40 
data = np.random.randint(5, 40, size = (12, 3))
df = pd.DataFrame(data, columns = ['random_no_1',
                                   'random_no_2',
                                   'random_no_3'])
  
# displaying random integers in the dataframe 
print(df)

Output :

Example 4 : Sorting random integers columns in Pandas Multiple Data frame column.




# importing pandas and numpy libraries
import numpy as np
import pandas as pd
  
# generating 6x2 i.e 12 random integers
# from 5 to 40 
data = np.random.randint(5, 40, size = (6, 2))
df = pd.DataFrame(data, columns = ['random_col_1', 'random_col_2'])
  
# displaying random integers in data frame 
print("Before Sorting :")
print(df)
  
# Sorting both Random integer column 
# First column 1 is sorted 
# then for every column 1, column 2 is sorted 
# in ascending order
# using dataframe.sort_values()
df.sort_values(['random_col_1', 'random_col_2'], axis = 0
               ascending = [True, True], inplace = True)
  
print("After Sorting :")
print(df)

Output :


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!