gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
How to sample on a column in a dataframe keeping same sample everytime a run
- User
How to sample on a column in a dataframe keeping same sample everytime a run
- Assistant
To sample a column in a DataFrame while keeping the same sample across different runs, you can set a random seed using NumPy or pandas. This ensures that the random number generation is reproducible. Below is an example using Python's pandas library.
Example
Let's assume you have a DataFrame and you want to sample from a specific column, say "column_name".
import pandas as pd import numpy as np # Sample DataFrame creation data = { 'column_name': ['A', 'B', 'C', 'D', 'E'], 'value': [1, 2, 3, 4, 5] } df = pd.DataFrame(data) # Set a seed for reproducibility np.random.seed(42) # Sample from 'column_name' sampled_data = df['column_name'].sample(n=3, random_state=42) # random_state can also be used here print(sampled_data)Key Details:
- Setting the Seed: The function ensures that the random choices will be the same every time the code is run.