Sample
df.sample(n, replace=False)
Randomly samples n
rows from df
.
- Input:
- df : DataFrame
- DataFrame to sample from.
- n : integer
- Number of rows to draw.
- replace : boolean, default False
- If True, rows are selected with replacement. If False, rows are selected without replacement.
- Returns:
- A random sample of
n
rows fromdf
- Return Type:
- DataFrame
- Note:
- If
replace = False
,n
must be smaller than the length of the DataFrame. Otherwise, the function will raise aValueError: Cannot take a larger sample than length of DataFrame when 'replace=False'
.
- If
pets.sample(3, replace=True)
Index | ID | Unnamed: 0 | Species | Color | Weight | Age | Is_Cat | Owner_Comment |
---|---|---|---|---|---|---|---|---|
4 | dog_003 | 4 | dog | black | 25 | 0.5 | False | Be the person your dog thinks you are. |
6 | ham_002 | 6 | hamster | golden | 0.25 | 0.2 | False | No, thank you! |
1 | cat_001 | 1 | cat | golden | 1.5 | 0.2 | True | My best birthday present ever!!! |
pets.sample(3, replace=False)
Index | ID | Unnamed: 0 | Species | Color | Weight | Age | Is_Cat | Owner_Comment |
---|---|---|---|---|---|---|---|---|
1 | cat_001 | 1 | cat | golden | 1.5 | 0.2 | True | My best birthday present ever!!! |
6 | ham_002 | 6 | hamster | golden | 0.25 | 0.2 | False | No, thank you! |
4 | dog_003 | 4 | dog | black | 25 | 0.5 | False | Be the person your dog thinks you are. |
pets.shape[0]
8
pets.sample(9, replace=False)
ValueError: Cannot take a larger sample than length of DataFrame when 'replace=False'