gpt-4-0314· openai
Suzhen/CodeChat
I have a dataframe with a string column. I want to create boolean (or one-hot) columns…
- 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?
- 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:- First, import the necessary library:
import pandas as pd- Then, create a sample dataframe with a string column:
data = {'Category': ['A', 'B', 'A', 'C', 'B', 'A', 'C']} df = pd.DataFrame(data)- Use the
get_dummies()function to create one-hot columns:
df_one_hot = pd.get_dummies(df, columns=['Category'])- Now, the
df_one_hotdataframe 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 1The
get_dummies()function is efficient and provides good performance for creating one-hot columns in pandas.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.