0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DataFrameの列(行)番号を指定してラベルを変更 Pandas.DataFrame

Last updated at Posted at 2022-06-27

はじめに

pandas.DataFrameのカラム名やインデックス名を変えたいけどpd.rename()をつかうにはdf.rename(columns={'before': 'after'}, index={'before': 'after'})のように「これまでの名前」と「これからの名前」が必要になるのが面倒。

そこで列番号(行番号)を指定して名前を変更する関数を定義してみる。

pandasのインポート

import pandas as pd

関数の定義

def rename_iaxis(dataframe, axis, n, name):
    # axis = 0ならインデックス、axis = 1ならカラムの名前をリスト化する
    if axis == 0:
        org_namelist = list(dataframe.index)
    elif axis == 1:
        org_namelist = list(dataframe.columns)
    
    # 名前のリストのn番目をnameに変更する
    new_namelist = org_namelist
    new_namelist[n] = name
    
    # dataframeのラベルを変更する
    dataframe = dataframe.set_axis(new_namelist, axis = axis, inplace = False)
    
    # データフレームを返す
    return dataframe

呼び出し

# pandas DataFrameを作成する
org_dict = {"a":[1,2,3],"b":[4,5,6],"c":[7,8,9]}
org_df = pd.DataFrame(org_dict)
print(org_df)

#    a  b  c
# 0  1  4  7
# 1  2  5  8
# 2  3  6  9


# 1番のカラム名をzに変更する
new_df = rename_iaxis(dataframe = org_df, axis = 1, n = 1, name = "z")
print(new_df)

#    a  z  c
# 0  1  4  7
# 1  2  5  8
# 2  3  6  9

これでいくらか名前を変えるハードルが下がった???

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?