← retour aux snippets

pandas: sample (frac, random_state)

Échantillonner des lignes de manière reproductible.

python pandas #pandas#sample#random

objectif

Échantillonner des lignes de manière reproductible.

code minimal

import pandas as pd
df = pd.DataFrame({"x":range(100)})
print(df.sample(frac=0.1, random_state=0).shape[0])

utilisation

import pandas as pd
df = pd.DataFrame({"g":[0,0,1,1]})
print(df.groupby("g", group_keys=False).apply(lambda d: d.sample(n=1, random_state=0)).shape[0])

variante(s) utile(s)

import pandas as pd
df = pd.DataFrame({"x":range(5)})
print(df.sample(n=2, random_state=1).shape[0])

notes

  • Toujours fixer random_state pour réplicabilité.