Renaming columns in pandas

前端 未结 27 3003
野性不改
野性不改 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:12

    Let's Understand renaming by a small example...

    1.Renaming columns using mapping:

    df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) #creating a df with column name A and B
    df.rename({"A": "new_a", "B": "new_b"},axis='columns',inplace =True) #renaming column A with 'new_a' and B with 'new_b'
    
    output:
       new_a  new_b
    0  1       4
    1  2       5
    2  3       6
    

    2.Renaming index/Row_Name using mapping:

    df.rename({0: "x", 1: "y", 2: "z"},axis='index',inplace =True) #Row name are getting replaced by 'x','y','z'.
    
    output:
           new_a  new_b
        x  1       4
        y  2       5
        z  3       6
    

提交回复
热议问题