Remove last two characters from column names of all the columns in Dataframe - Pandas

后端 未结 2 1833
花落未央
花落未央 2021-01-19 01:40

I am joining the two dataframes (a,b) with identical columns / column names using the user ID key and while joining, I had to give suffix characters, in order for it to get

2条回答
  •  攒了一身酷
    2021-01-19 02:17

    This snippet should get the job done :

    df.columns = pd.Index(map(lambda x : str(x)[:-2], df.columns))
    

    Edit : This is a better way to do it

    df.rename(columns = lambda x : str(x)[:-2])
    

    In both cases, all we're doing is iterating through the columns and apply some function. In this case, the function converts something into a string and takes everything up until the last two characters.

    I'm sure there are a few other ways you could do this.

提交回复
热议问题