Renaming columns in pandas

前端 未结 27 3030
野性不改
野性不改 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条回答
  •  深忆病人
    2020-11-21 07:21

    Let's say this is your dataframe.

    You can rename the columns using two methods.

    1. Using dataframe.columns=[#list]

      df.columns=['a','b','c','d','e']
      

      The limitation of this method is that if one column has to be changed, full column list has to be passed. Also, this method is not applicable on index labels. For example, if you passed this:

      df.columns = ['a','b','c','d']
      

      This will throw an error. Length mismatch: Expected axis has 5 elements, new values have 4 elements.

    2. Another method is the Pandas rename() method which is used to rename any index, column or row

      df = df.rename(columns={'$a':'a'})
      

    Similarly, you can change any rows or columns.

提交回复
热议问题