19_Pandas随机抽取行和列的样本(sample)
在检查具有许多行的pandas.DataFrame,pandas.Series的数据时,使用sample()方法随机抽取行或列(随机抽样)很方便。
还有其他方法可用于检查pandas.DataFrame和pandas.Series数据,head()和tail(),它们会返回第一行和最后一行。
请参见以下文章。
将描述以下内容。
- sample()的默认行为
- 指定要提取的行数和列数:参数n
- 指定要提取的行和列的比例:参数frac
- 固定随机:参数random_state
- 允许重复:参数replace
- 指定行/列:参数axis
使用seaborn中的iris数据集作为样本。
import pandas as pd
import seaborn as sns
df = sns.load_dataset("iris")
print(df.shape)
# (150, 5)
sample()的默认行为
如果未提供任何参数,则将随机返回一行。
print(df.sample())
# sepal_length sepal_width petal_length petal_width species
# 108 6.7 2.5 5.8 1.8 virginica
指定要提取的行数和列数:参数n
可以使用参数n指定要提取的行数和列数。
print(df.sample(n=3))
# sepal_length sepal_width petal_length petal_width species
# 3 4.6 3.1 1.5 0.2 setosa
# 1 4.9 3.0 1.4 0.2 setosa
# 96 5.7 2.9 4.2 1.3 versicolor
指定要提取的行和列的比例:参数frac
可以使用参数frac指定要提取的行和列的比率。 1是100%。不能同时指定n和frac。
print(df.sample(frac=0.04))
# sepal_length sepal_width petal_length petal_width species
# 119 6.0 2.2 5.0 1.5 virginica
# 97 6.2 2.9 4.3 1.3 versicolor
# 46 5.1 3.8 1.6 0.2 setosa
# 137 6.4 3.1 5.5 1.8 virginica
# 56 6.3 3.3 4.7 1.6 versicolor
# 62 6.0 2.2 4.0 1.0 versicolor
固定随机:参数random_state
可以使用参数random_state指定随机数。随机数是固定的,因此总是返回相同的行和列。
print(df.sample(n=3, random_state=0))
# sepal_length sepal_width petal_length petal_width species
# 114 5.8 2.8 5.1 2.4 virginica
# 62 6.0 2.2 4.0 1.0 versicolor
# 33 5.5 4.2 1.4 0.2 setosa
允许重复:参数replace
如果参数replace设置为True,则允许重复的行/列。默认值为False。
如果replace = True,则可以指定比原始行和列数更多的采样数。
print(df.head(3).sample(n=3, replace=True))
# sepal_length sepal_width petal_length petal_width species
# 2 4.7 3.2 1.3 0.2 setosa
# 1 4.9 3.0 1.4 0.2 setosa
# 1 4.9 3.0 1.4 0.2 setosa
print(df.head(3).sample(n=5, replace=True))
# sepal_length sepal_width petal_length petal_width species
# 1 4.9 3.0 1.4 0.2 setosa
# 0 5.1 3.5 1.4 0.2 setosa
# 1 4.9 3.0 1.4 0.2 setosa
# 0 5.1 3.5 1.4 0.2 setosa
# 0 5.1 3.5 1.4 0.2 setosa
指定行/列:参数axis
如果参数轴为1,则可以随机提取列。与到目前为止的示例一样,默认值为0(行)。
print(df.head().sample(n=2, axis=1))
# sepal_width species
# 0 3.5 setosa
# 1 3.0 setosa
# 2 3.2 setosa
# 3 3.1 setosa
# 4 3.6 setosa