Random Row Selection from DataFrame by Column

  • Share this:

Code introduction


This function randomly selects a row from a given pandas DataFrame based on a specified column name.


Technology Stack : pandas

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_select_from_dataframe(df, column_name):
    """
    Select a random row from a DataFrame based on a specified column.
    
    Args:
    df (pandas.DataFrame): The DataFrame to select a random row from.
    column_name (str): The name of the column to filter by.
    
    Returns:
    pandas.Series: A random row from the DataFrame filtered by the specified column.
    """
    # Filter the DataFrame based on the specified column
    filtered_df = df[df[column_name] != None]
    
    # Select a random row from the filtered DataFrame
    random_row = filtered_df.sample(n=1)
    
    return random_row                
              
Tags: