Example of how to select randomly (sample) the rows of a dataframe using pandas in python:
1 -- Create a simple dataframe
Créons une simple dataframe avec 5 colonnes et 20 lignes:
>>> import pandas as pd>>> import numpy as np>>> data = np.arange(1,101)>>> data = data.reshape(20,5)>>> df = pd.DataFrame(data=data,columns=['a','b','c','d','e'])>>> dfa b c d e0 1 2 3 4 51 6 7 8 9 102 11 12 13 14 153 16 17 18 19 204 21 22 23 24 255 26 27 28 29 306 31 32 33 34 357 36 37 38 39 408 41 42 43 44 459 46 47 48 49 5010 51 52 53 54 5511 56 57 58 59 6012 61 62 63 64 6513 66 67 68 69 7014 71 72 73 74 7515 76 77 78 79 8016 81 82 83 84 8517 86 87 88 89 9018 91 92 93 94 9519 96 97 98 99 100
2 -- Select randomly rows using the function sample()
To sample a dataframe using pandas, a solution is ti use pandas.DataFrame.sample. Example: let's randomly select 5 rows from the dataframe df defined above:
>>> df_sub_cutoff = df.sample(n=5)>>> df_sub_cutoffa b c d e11 56 57 58 59 600 1 2 3 4 518 91 92 93 94 9515 76 77 78 79 809 46 47 48 49 50
Lets create another sample of size n=5
>>> df_sub_cutoff = df.sample(n=5)>>> df_sub_cutoffa b c d e0 1 2 3 4 54 21 22 23 24 2512 61 62 63 64 655 26 27 28 29 3016 81 82 83 84 85
or of size n=2:
>>> df_sub_cutoff = df.sample(n=2)>>> df_sub_cutoffa b c d e0 1 2 3 4 515 76 77 78 79 80
Note: to always get the same sample, a solution is to use the option "random_state" (with random_state=42 for example):
>>> df_sub_cutoff = df.sample(n=5, random_state = 42)>>> df_sub_cutoffa b c d e0 1 2 3 4 517 86 87 88 89 9015 76 77 78 79 801 6 7 8 9 108 41 42 43 44 45
Lets do it again using random_state = 42, to check that we got the same sample:
>>> df_sub_cutoff = df.sample(n=5, random_state = 42)>>> df_sub_cutoffa b c d e0 1 2 3 4 517 86 87 88 89 9015 76 77 78 79 801 6 7 8 9 108 41 42 43 44 45
