你可以使用下面的基本语法来从pandas DataFrame中随机抽取行:
#randomly select one row
df.sample()
#randomly select n rows
df.sample(n=5)
#randomly select n rows with repeats allowed
df.sample(n=5, replace=True)
#randomly select a fraction of the total rows
df.sample(frac=0.3)
#randomly select n rows by group
df.groupby('team', group_keys=False).apply(lambda x: x.sample(2))
下面的例子展示了如何在实践中使用这个语法,并使用以下pandas DataFrame:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'points': [25, 12, 15, 14, 19, 23, 25, 29],
'assists': [5, 7, 7, 9, 12, 9, 9, 4],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
#view DataFrame
df
team points assists rebounds
0 A 25 5 11
1 A 12 7 8
2 A 15 7 10
3 A 14 9 6
4 B 19 12 6
5 B 23 9 5
6 B 25 9 9
7 B 29 4 12
例1:随机选择一条行
下面的代码展示了如何从DataFrame中随机抽取一条记录:
#randomly select one row
df.sample()
team points assists rebounds
5 B 23 9 5
例2:随机选择n行
下面的代码显示了如何从DataFrame中随机选择n行:
#randomly select n rows
df.sample(n=5)
team points assists rebounds
5 B 23 9 5
2 A 15 7 10
4 B 19 12 6
6 B 25 9 9
1 A 12 7 8
例3:随机选择n条允许重复的行
下面的代码显示了如何从DataFrame中随机选择n行,并允许重复行:
#randomly select 5 rows with repeats allowed
df.sample(n=5, replace=True)
team points assists rebounds
6 B 25 9 9
7 B 29 4 12
5 B 23 9 5
1 A 12 7 8
5 B 23 9 5
例子4:随机选择总行数的一小部分
下面的代码显示了如何从DataFrame中随机选择总行数的一小部分:
#randomly select 25% of rows
df.sample(frac=0.25)
team points assists rebounds
2 A 15 7 10
1 A 12 7 8
例5:按组随机选择n条行
下面的代码显示了如何从DataFrame中按组随机选择n条记录:
#randomly select 2 rows from each team
df.groupby('team', group_keys=False).apply(lambda x: x.sample(2))
team points assists rebounds
0 A 25 5 11
2 A 15 7 10
7 B 29 4 12
4 B 19 12 6
注意,从'A'组的2条记录和'B'组的2条记录被随机抽出。
注意:你可以在这里找到pandas sample()函数的完整文档。
其他资源
下面的教程解释了如何在Pandas中执行其他常见的抽样方法: