Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

I have a dataframe with a string column. I want to create boolean (or one-hot) columns…

  1. User

    I have a dataframe with a string column. I want to create boolean (or one-hot) columns starting from the string column in pandas, how can I do that quickly and with high performance?

  2. Assistant

    You can use the get_dummies() function in pandas to create one-hot (or boolean) columns quickly and efficiently. Here's how to do it:

    1. First, import the necessary library:
    import pandas as pd
    
    1. Then, create a sample dataframe with a string column:
    data = {'Category': ['A', 'B', 'A', 'C', 'B', 'A', 'C']}
    df = pd.DataFrame(data)
    
    1. Use the get_dummies() function to create one-hot columns:
    df_one_hot = pd.get_dummies(df, columns=['Category'])
    
    1. Now, the df_one_hot dataframe will have one-hot columns for each unique value in the 'Category' column:
    print(df_one_hot)
    

    Output:

       Category_A  Category_B  Category_C
    0           1           0           0
    1           0           1           0
    2           1           0           0
    3           0           0           1
    4           0           1           0
    5           1           0           0
    6           0           0           1
    

    The get_dummies() function is efficient and provides good performance for creating one-hot columns in pandas.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.