Renaming columns in pandas

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

    Note that these approach do not work for a MultiIndex. For a MultiIndex, you need to do something like the following:

    >>> df = pd.DataFrame({('$a','$x'):[1,2], ('$b','$y'): [3,4], ('e','f'):[5,6]})
    >>> df
       $a $b  e
       $x $y  f
    0  1  3  5
    1  2  4  6
    >>> rename = {('$a','$x'):('a','x'), ('$b','$y'):('b','y')}
    >>> df.columns = pandas.MultiIndex.from_tuples([
            rename.get(item, item) for item in df.columns.tolist()])
    >>> df
       a  b  e
       x  y  f
    0  1  3  5
    1  2  4  6
    

提交回复
热议问题