Renaming columns in pandas

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

    df = pd.DataFrame({'$a': [1], '$b': [1], '$c': [1], '$d': [1], '$e': [1]})
    

    If your new list of columns is in the same order as the existing columns, the assignment is simple:

    new_cols = ['a', 'b', 'c', 'd', 'e']
    df.columns = new_cols
    >>> df
       a  b  c  d  e
    0  1  1  1  1  1
    

    If you had a dictionary keyed on old column names to new column names, you could do the following:

    d = {'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}
    df.columns = df.columns.map(lambda col: d[col])  # Or `.map(d.get)` as pointed out by @PiRSquared.
    >>> df
       a  b  c  d  e
    0  1  1  1  1  1
    

    If you don't have a list or dictionary mapping, you could strip the leading $ symbol via a list comprehension:

    df.columns = [col[1:] if col[0] == '$' else col for col in df]
    

提交回复
热议问题