Search code examples
pythonpandasdummy-variable

how to rename a dataframe column which is a digit like name?


I have a dataframe column contains 10 different digits. Through pd.get_dummies I've got 10 new columns which column names are numbers. Then I want to rename these number named columns by df = df.rename(columns={'0':'topic0'}) but failed. How can I rename these columns' name from numbers to strings?


Solution

  • Use DataFrame.add_prefix:

    df = pd.DataFrame({'col':[1,5,7,8,3,6,5,8,9,10]})
    
    df1 = pd.get_dummies(df['col']).add_prefix('topic')
    print (df1)
       topic1  topic3  topic5  topic6  topic7  topic8  topic9  topic10
    0       1       0       0       0       0       0       0        0
    1       0       0       1       0       0       0       0        0
    2       0       0       0       0       1       0       0        0
    3       0       0       0       0       0       1       0        0
    4       0       1       0       0       0       0       0        0
    5       0       0       0       1       0       0       0        0
    6       0       0       1       0       0       0       0        0
    7       0       0       0       0       0       1       0        0
    8       0       0       0       0       0       0       1        0
    9       0       0       0       0       0       0       0        1