0

I have been trying to create a dummies of the categorical variable "SEX" in my dataset. I want to change the names of generated dummy columns . But I could see there is an option of changing only the prefix of column name but couldn't find any way to change the entire name. Can anyone help me out?

enter image description here

My code for the above output is:

print(df['SEX'].value_counts())

dummy_variable=pd.get_dummies(df['SEX']).rename(columns=lambda x:'SEX_' +str(x))

print(dummy_variable)

I desired to have the output dummy column names as SEX_MALE and SEX_FEMALE.

Thanks in advance.

furas
  • 134,197
  • 12
  • 106
  • 148
Mahesh
  • 21
  • 1
  • 2
  • 1
    Does this answer your question? [Rename specific column(s) in pandas](https://stackoverflow.com/questions/19758364/rename-specific-columns-in-pandas) – AMC May 05 '21 at 17:42
  • Also: https://stackoverflow.com/q/11346283 – AMC May 05 '21 at 17:43
  • Well if you wanna rename columns automatically generated by get_dummies, I suggest you use the get_dummies(data['column_name'], prefix = 'pre_') You can add fstrings to this to generate names dynamically. – Naman Bansal Mar 07 '23 at 20:09

2 Answers2

-1

Try:

df = df.rename(columns = {'SEX_1': 'SEX_MALE', 'SEX_2': 'SEX_FEMALE'})
Nk03
  • 14,699
  • 2
  • 8
  • 22
  • 3
    Hi Naman, Is there any way to change the names in dummy variable itself.i mean before adding to dataset. – Mahesh May 05 '21 at 12:51
-1

I'm not sure if this is what you mean, but by doing this you should be able to change the columns names:

dummy_variable.rename(columns = {'SEX_1': 'SEX_MALE', 'SEX_2': 'SEX_FEMALE'}, inplace = False)
Sergio García
  • 486
  • 5
  • 15