1. 程式人生 > 程式設計 >修改Pandas的行或列的名字(重新命名)

修改Pandas的行或列的名字(重新命名)

pandas.DataFrame.rename

使用函式:DataFrame.rename(mapper=None,index=None,columns=None,axis=None,copy=True,inplace=False,level=None)

功能:更改軸標籤

函式字典值必須是唯一的(1對1)。未包含在 字典/Series 中的標籤將保留原樣。列出的額外標籤不會引發錯誤。

引數:

mapper,index,columns : dict-like or function,optional

dict-like or functions transformations to apply to that axis' values. Use either mapperand axis to specify the axis to target with mapper,or index and columns.

dict-like 或函式轉換以應用於該軸的值。二者必選其一mapper,並使用axis指定軸與目標mapper,或index和 columns。

主要用於指定需要修改的地方:index or columns

axis : int or str,optional

Axis to target with mapper. Can be either the axis name (‘index',‘columns') or number (0,1). The default is ‘index'.

軸與目標mapper。可以是軸名稱('index','columns')或數字(0,1)。預設為'index'。

copy : boolean,default True

Also copy underlying data

還複製基礎資料

inplace : boolean,default False

Whether to return a new DataFrame. If True then value of copy is ignored.

是否返回新的DataFrame。如果為True,則忽略複製值。

level : int or level name,default None

In case of a MultiIndex,only rename labels in the specified level.

如果是MultiIndex,只重新命名指定級別的標籤。

返回:

renamed : DataFrame

例子

DataFrame.rename支援兩種呼叫約定

  • (index=index_mapper,columns=columns_mapper,...)
  • (mapper,axis={'index','columns'},...)

我們強烈建議您使用關鍵字引數來闡明您的意圖。

>>> df = pd.DataFrame({"A": [1,2,3],"B": [4,5,6]})
>>> df.rename(index=str,columns={"A": "a","B": "c"})
  a c
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str,"C": "c"})
  a B
0 1 4
1 2 5
2 3 6
 
 
#使用軸樣式引數
 
>>> df.rename(str.lower,axis='columns')
  a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2,2: 4},axis='index')
  A B
0 1 4
2 2 5
4 3 6

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。