如何从Pandas DataFrame中随机选择行

如何从Pandas DataFrame中随机选择行

让我们来讨论如何从Pandas DataFrame中随机选择行。从DataFrame中随机选择行可以通过不同的方式实现。
创建一个简单的数据框架,其中有列表的字典。

# Import pandas package
import pandas as pd
  
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'],
        'Age':[27, 24, 22, 32, 15],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# select all columns
df

如何从Pandas DataFrame中随机选择行

方法一:使用 sample() 方法

Sample方法从一个轴的对象中返回一个随机的样本,这个对象的类型与你的调用者相同。

示例 1:

# Selects one row randomly using sample()
# without give any parameters.
 
# Import pandas package
import pandas as pd
  
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'],
        'Age':[27, 24, 22, 32, 15],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Select one row randomly using sample()
# without give any parameters
df.sample()

输出:

如何从Pandas DataFrame中随机选择行

例子2:使用参数n ,随机选择n个行。
使用sample(n)或sample(n=n)随机选择n数量的行。每次你运行这个,你都会得到n个不同的行。

# To get 3 random rows
# each time it gives 3 different rows
 
# df.sample(3) or
df.sample(n = 3)

输出:

如何从Pandas DataFrame中随机选择行

例子3:使用frac参数。
我们可以对轴上的项目进行分数处理,然后得到行数。例如,如果frac=.5,那么sample方法将返回50%的行。

# Fraction of rows
 
# here you get .50 % of the rows
df.sample(frac = 0.5)

输出:

如何从Pandas DataFrame中随机选择行

示例 4:
首先选择整个df数据框架的70%的行,并放入另一个数据框架df1,然后我们从df1中选择50%的frac。

# fraction of rows
 
# here you get 70 % row from the df
# make put into another dataframe df1
df1 = df.sample(frac =.7)
 
# Now select 50 % rows from df1
df1.sample(frac =.50)

输出:

如何从Pandas DataFrame中随机选择行

例子5:随机选择一些行,替换=false
参数replace允许多次选择一个行(如)。sample()方法的替换参数的默认值是假的,所以你永远不会选择超过总行数的行。

# Dataframe df has only 4 rows
 
# if we try to select more than 4 row then will come error
# Cannot take a larger sample than population when 'replace = False'
df1.sample(n = 3, replace = False)

输出:

如何从Pandas DataFrame中随机选择行

例子6:选择多于n行,其中n是借助替换的总行数。

# Select more than rows with using replace
# default it is False
df1.sample(n = 6, replace = True)

输出:

如何从Pandas DataFrame中随机选择行

例子7:使用权重

# Weights will be re-normalized automatically
test_weights = [0.2, 0.2, 0.2, 0.4]
 
df1.sample(n = 3, weights = test_weights)

输出:

如何从Pandas DataFrame中随机选择行

例子8:使用轴线
sample()方法还允许用户使用axis参数对列而不是行进行采样。

# Accepts axis number or name.
 
# sample also allows users to sample columns
# instead of rows using the axis argument.
df1.sample(axis = 0)

输出:

如何从Pandas DataFrame中随机选择行

实例9:使用random_state
对于一个给定的DataFrame,该样本将总是获取相同的行。如果random_state是None或者np.random,那么就会返回一个随机初始化的RandomState对象。

# With a given seed, the sample will always draw the same rows.
 
# If random_state is None or np.random,
# then a randomly-initialized
# RandomState object is returned.
df1.sample(n = 2, random_state = 2)

输出:

如何从Pandas DataFrame中随机选择行

方法二: 使用NumPy
Numpy选择包括多少个索引进行随机选择,我们可以允许替换。

# Import pandas & Numpy package
import numpy as np
import pandas as pd
  
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'],
        'Age':[27, 24, 22, 32, 15],
        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'],
        'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Choose how many index include for random selection
chosen_idx = np.random.choice(4, replace = True, size = 6)
 
df2 = df.iloc[chosen_idx]
 
df2

输出:

如何从Pandas DataFrame中随机选择行

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程