Phương thức đổi tên khung dữ liệu Pandas ()
Ví dụ
Đổi tên các chỉ mục hàng của DataFrame:
import pandas as pd
data = {
"age": [50, 40, 30],
"qualified":
[True, False, False]
}
idx = ["Sally", "Mary", "John"]
df =
pd.DataFrame(data, index=idx)
newdf = df.rename({"Sally": "Pete",
"Mary": "Patrick", "John": "Paula"})
print(newdf)
Hãy tự mình thử »Định nghĩa và cách sử dụng
Phương thức rename()
cho phép bạn thay đổi chỉ mục hàng và nhãn cột.
Cú pháp
dataframe .rename( mapper , index, columns, axis, copy,
inplace, level, errors)
Thông số
Các index
, columns
, axis
, copy
, inplace
, level
, errors
là các đối số từ khóa .
Parameter | Value | Description |
---|---|---|
mapper | Optional. A dictionary where the old index/label is the key and the new index/label is the value | |
index | old and new indexes as key/value pairs | Optional. A dictionary where the old index is the key and the new index is the value |
columns | old and new labels as key/value pairs | Optional. A dictionary where the old label is the key and the new label is the value |
axis | 0 | Optional, default 0. The axis to perform the renaming (important if the mapper parameter is present and index or columns are not) |
copy | True | Optional, default True. Whether to also copy underlying data or not |
inplace | True | Optional, default False. If True: the operation is done on the current DataFrame. If False: returns a copy where the operation is done. |
level | Number Label | Optional, specifies which level to rename when working with MultiIndex DataFrames |
errors | 'ignore' | Optional, default 'ignore'. Specifies whether or not to return an error if no such index/label is present in the DataFrame |
Giá trị trả về
DataFrame có kết quả hoặc Không có nếu tham số tại chỗ được đặt thành True.
Hàm này KHÔNG thực hiện thay đổi đối tượng DataFrame ban đầu.