Renaming columns in pandas

前端 未结 27 2638
野性不改
野性不改 2020-11-21 07:05

I have a DataFrame using pandas and column labels that I need to edit to replace the original column labels.

I\'d like to change the column names in a DataFrame

27条回答
  •  猫巷女王i
    2020-11-21 07:37

    If you have to deal with loads of columns named by the providing system out of your control, I came up with the following approach that is a combination of a general approach and specific replacments in one go.

    First create a dictionary from the dataframe column names using regex expressions in order to throw away certain appendixes of column names and then add specific replacements to the dictionary to name core columns as expected later in the receiving database.

    This is then applied to the dataframe in one go.

    dict=dict(zip(df.columns,df.columns.str.replace('(:S$|:C1$|:L$|:D$|\.Serial:L$)','')))
    dict['brand_timeseries:C1']='BTS'
    dict['respid:L']='RespID'
    dict['country:C1']='CountryID'
    dict['pim1:D']='pim_actual'
    df.rename(columns=dict, inplace=True)
    

提交回复
热议问题