← retour aux snippets

pandas: sample reproductible

Échantillonner des lignes avec graine fixe.

python pandas #pandas#sample#random

objectif

Échantillonner des lignes avec graine fixe.

code minimal

import pandas as pd
df = pd.DataFrame({"x":range(10)})
print(len(df.sample(n=3, random_state=42)) == 3)

utilisation

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

variante(s) utile(s)

import pandas as pd
print(pd.Series(range(5)).sample(n=2, random_state=1).tolist())

notes

  • Fixer random_state pour reproductibilité entre runs.