Relabeling and Naming
Table of contents
import pandas as pd
‘ReLabeling’ (renaming)
rename()
Alter axes labels. (usually column labels)
Recommanded use only for ‘relabeling’ column.
For ‘relabeling’ index, use set_index()
below.
DataFrame.rename(mapper, axis, | index, columns, inplace) # row/column label 변경
Series.rename(index, inplace)
Index.rename(name, inplace)
- mapper : dict-like or function
- axis : {0 or ‘index’, 1 or ‘columns’}, default 0
- index : dict-like or function
- columns : dict-like or function
- inplace : bool, default False
set_index()
$\longleftrightarrow$ reset_index()
set_index()
: Set the index (row labels and name) using one or more existing columns or arrays(of the correct length).
dataframe.set_index(keys, inplace=False) # 기존 index 를 columns 중 하나로 대체
- keys : label or array-like or list of labels/arrays
- label of a column / list of labels of columns
- List-like (of the correct length)
(cf) set index()
사용 시 기존의 index 는 삭제됨.
dataframe['new_column_name'] = dataframe.index
dataframe.set_index('coloumn_name', inplace=True)
>>> dataframe
# 기존의 index 를 새로운 칼럼에 저장하고,
# 기존의 column 중 하나로 index 를 대체.
reset_index()
: Reset(remove) the index, or a level of it.
dataframe.reset_index(level=None, drop=False, inplace=False) # opposite of set_index()
- level : int, str, tuple, or list, default None
- Only remove the given levels from the index. Removes all levels by default.
- drop : bool, default False
- Do not try to insert index into dataframe columns. This resets the index to the default integer index.
- inplace : bool, default False
‘Naming’ (renaming)
dataframe.index.name
(attribute)
dataframe.index.name = 'row_axis_name'
pandas.Index.name
→ ‘name’ of row_axis
pandas.Series.name
→ ‘label’ of row/column
rename_axis()
Set the ‘name’ of the axis for the index or columns.
DataFrame.rename_axis(mapper, axis, | index, columns, inplace) # row/column label 변경
Series.rename_axis(mapper, axis, | index, inplace)
>>> dataframe.rename_axis("wines", axis='rows').rename_axis("fields", axis='columns')
fields country designation points price
wines
0 Italy Vulkà Bianco 87 NaN
... ... ... ... ...
- mapper : scalar, list-like, optional
- axis : {0 or ‘index’, 1 or ‘columns’}, default 0
- index : scalar, list-like, dict-like or function, optional
- columns : scalar, list-like, dict-like or function, optional
- inplace : bool, default False