📜  在 Pandas Dataframe 中生成随机整数

📅  最后修改于: 2022-05-13 01:55:17.925000             🧑  作者: Mango

在 Pandas Dataframe 中生成随机整数

Pandas 是最流行的用于数据分析的Python库。它通过完全用 C 或Python编写的后端源代码提供高度优化的性能。

在这里,我们将看到如何在 Pandas 数据报中生成随机整数。我们将使用numpy.random.randint()方法来生成随机整数。

示例 1:在 Pandas 单一数据框列中生成随机整数。

# 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)

输出 :

示例 2 :对 Pandas 单数据框列中的列进行排序。

# 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)

输出 :

示例 3:在 Pandas 多数据框列中生成随机整数。

# 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)

输出 :

示例 4:对 Pandas 多数据框列中的随机整数列进行排序。

# 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)

输出 :