Renaming columns in pandas

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

    I know this question and answer has been chewed to death. But I referred to it for inspiration for one of the problem I was having . I was able to solve it using bits and pieces from different answers hence providing my response in case anyone needs it.

    My method is generic wherein you can add additional delimiters by comma separating delimiters= variable and future-proof it.

    Working Code:

    import pandas as pd
    import re
    
    
    df = pd.DataFrame({'$a':[1,2], '$b': [3,4],'$c':[5,6], '$d': [7,8], '$e': [9,10]})
    
    delimiters = '$'
    matchPattern = '|'.join(map(re.escape, delimiters))
    df.columns = [re.split(matchPattern, i)[1] for i in df.columns ]
    

    Output:

    >>> df
       $a  $b  $c  $d  $e
    0   1   3   5   7   9
    1   2   4   6   8  10
    
    >>> df
       a  b  c  d   e
    0  1  3  5  7   9
    1  2  4  6  8  10
    

提交回复
热议问题