パンダの列とインデックスを名前変更

時々、PandasのDataFrameオブジェクトで列やインデックスの名前を変更したい場合があります。列やインデックスの名前を変更するためには、pandas DataFrameのrename()関数を使用することができます。この関数は以下のパラメータをサポートしています。

  • mapper: dictionary or a function to apply on the columns and indexes. The ‘axis’ parameter determines the target axis – columns or indexes.
  • index: must be a dictionary or function to change the index names.
  • columns: must be a dictionary or function to change the column names.
  • axis: can be int or string. It’s used with ‘mapper’ parameter to define the target axis. The allowed values are (‘index’, ‘columns’) or number (0, 1). The default value is ‘index’.
  • inplace: if True, the DataFrame is changed. Otherwise, a new DataFrame is returned and the current DataFrame remains unchanged. The default value is ‘False’.
  • level: can be int or level name. It’s used in case of a MultiIndex, only rename labels in the specified level.
  • errors: possible values are (‘ignore’, ‘raise’), default is ‘ignore’. If specified as ‘raise’ then KeyError is raised when a dict-like ‘mapper’, ‘index’, or ‘columns’ contains labels that are not present in the Index being transformed. If ‘ignore’, existing keys will be renamed and extra keys will be ignored.

rename()関数についてのいくつかの重要なポイント。

    1. 意図を明確にするために、キーワード引数を使用することがおすすめです。

 

    この関数を使用して、辞書内の値によって、単一の列または複数の列の名前を変更することができます。

Pandasのrename()関数の使用例をいくつか見てみましょう。

1. パンダの列名を変更する。

import pandas as pd

d1 = {'Name': ['Pankaj', 'Lisa', 'David'], 'ID': [1, 2, 3], 'Role': ['CEO', 'Editor', 'Author']}

df = pd.DataFrame(d1)

print('Source DataFrame:\n', df)

# rename columns
df1 = df.rename(columns={'Name': 'EmpName', 'ID': 'EmpID', 'Role': 'EmpRole'})
print('Result DataFrame:\n', df1)

出力:

Source DataFrame:
      Name  ID    Role
0  Pankaj   1     CEO
1    Lisa   2  Editor
2   David   3  Author
Result DataFrame:
   EmpName  EmpID EmpRole
0  Pankaj      1     CEO
1    Lisa      2  Editor
2   David      3  Author

上記のrename()関数の呼び出しは、次のようにも書くことができます。

df1 = df.rename(mapper={'Name': 'EmpName', 'ID': 'EmpID', 'Role': 'EmpRole'},
                axis='columns')  # axis=1 corresponds to columns

キーワード引数を使用する方が、マッパーや軸引数を使用するよりも明確です。

2. パンダの1つのカラムの名前を変更する。

単一の列の名前を変更したい場合は、columns辞書パラメータに単一のキーと値のペアを渡すだけです。

df1 = df.rename(columns={'Name': 'EmpName'})
print(df1)

出力:

  EmpName  ID    Role
0  Pankaj   1     CEO
1    Lisa   2  Editor
2   David   3  Author

もし列の辞書に一致しないマッピングがある場合、結果は同じになります。

df1 = df.rename(columns={'Name': 'EmpName', 'X': 'Y'})  # same result since there is no X column

3. パンダのインデックス名を変更する。

インデックスの名前を変更したい場合は、’index’ パラメーターに辞書を渡してください。

df2 = df.rename(index={0: '#0', 1: '#1', 2: '#2'})
print('Renamed Indexes:\n', df2)

出力する。

Renamed Indexes:
       Name  ID    Role
#0  Pankaj   1     CEO
#1    Lisa   2  Editor
#2   David   3  Author

私たちは、マッパーや軸の引数を使用して、インデックスの名前を変更することもできます。

df2 = df.rename({0: '#0', 1: '#1', 2: '#2'}, axis=0)  
# axis='index' will work, first argument is assigned to 'mapper'

4. パンダの単一のインデックスの名前を変更する。 (Panda no tan’itsu no indekkusu no namae o henkō suru)

df2 = df.rename(index={1: '#1'})
print(df2)

出力:

      Name  ID    Role
0   Pankaj   1     CEO
#1    Lisa   2  Editor
2    David   3  Author

5. データフレームをインプレースで変更する

もしソースのDataFrame自体を変更したい場合は、inplace引数にTrueを渡してください。

import pandas as pd

d1 = {'Name': ['Pankaj', 'Lisa', 'David'], 'ID': [1, 2, 3], 'Role': ['CEO', 'Editor', 'Author']}

df = pd.DataFrame(d1)

print('Source DataFrame:\n', df)

df.rename(index={0: '#0', 1: '#1', 2: '#2'}, columns={'Name': 'EmpName', 'ID': 'EmpID', 'Role': 'EmpRole'}, inplace=True)

print('Source DataFrame:\n', df)

出力:

Source DataFrame:
      Name  ID    Role
0  Pankaj   1     CEO
1    Lisa   2  Editor
2   David   3  Author

Source DataFrame:
    EmpName  EmpID EmpRole
#0  Pankaj      1     CEO
#1    Lisa      2  Editor
#2   David      3  Author

6.カラムの名前を変更するためにマッパー関数を使用する。

df = pd.DataFrame({'NAME': ['Pankaj', 'Lisa'], 'ID': [1, 2], 'ROLE': ['CEO', 'Editor']})
print(df)

df.rename(mapper=str.lower, axis=1, inplace=True)
print(df)

出力:

     NAME  ID    ROLE
0  Pankaj   1     CEO
1    Lisa   2  Editor

     name  id    role
0  Pankaj   1     CEO
1    Lisa   2  Editor

7. 列やインデックスの名前を変更するための関数を使用する

import pandas as pd
import math

df = pd.DataFrame({'NAME': ['Pankaj', 'Lisa'], 'ID': [1, 2], 'ROLE': ['CEO', 'Editor']})

df.rename(columns=str.lower, index=math.degrees, inplace=True)
print(df)

出力:

            name  id    role
0.00000   Pankaj   1     CEO
57.29578    Lisa   2  Editor

8. 厳密な名前の変更とKeyErrorの発生

import pandas as pd

df = pd.DataFrame({'NAME': ['Pankaj', 'Lisa'], 'ID': [1, 2], 'ROLE': ['CEO', 'Editor']})

df1 = df.rename(columns={'Salary': 'EmpSalary'})  # unmatched mappings are ignored

df1 = df.rename(columns={'Salary': 'EmpSalary'}, errors='raise')  # unmatched mappings raising KeyError

出力:

Traceback (most recent call last):
  File "/Users/scdev/Documents/PycharmProjects/hello-world/scdev/pandas/pandas_rename_column.py", line 58, in <module>
    df1 = df.rename(columns={'Salary': 'EmpSalary'}, errors='raise')
KeyError: "['Salary'] not found in axis"

9. 参考文献

  • pandas DataFrame rename() API Doc
  • Python Pandas Module Tutorial
コメントを残す 0

Your email address will not be published. Required fields are marked *