【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
axis : int or str, optional
copy : boolean, default True
inplace : boolean, default False
level : int or level name, default None
|
---|
返回: |
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, columns={"A": "a", "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