Pandas: 辞書を使用して列の名前を変更する方法
次の基本構文を使用して、パンダの辞書を使用して列の名前を変更できます。
#define dictionary some_dict = {' old_col1 ': ' new_col1 ', ' old_col2 ': ' new_col2 ', ' old_col3 ': ' new_col3 '} #rename columns in DataFrame using dictionary df. rename (columns=some_dict, inplace= True )
注: 元の DataFrame の列名を変更するには、 inplace=Trueを指定する必要があります。
次の例は、この構文を実際に使用する方法を示しています。
例: 辞書を使用して Pandas の列の名前を変更する
次のパンダ データフレームがあるとします。
import pandas as pd #createDataFrame df = pd. DataFrame ({' rebounds ': [10, 14, 14, 13, 13, 12, 10, 7], ' points ': [30, 22, 19, 14, 14, 11, 20, 28], ' assists ': [5, 6, 6, 5, 8, 7, 7, 9]}) #view DataFrame print (df) rebound points assists 0 10 30 5 1 14 22 6 2 14 19 6 3 13 14 5 4 13 14 8 5 12 11 7 6 10 20 7 7 7 28 9
次の構文を使用すると、辞書を使用して DataFrame 内の各列の名前を変更できます。
#define dictionary with new column names
some_dict = {' rebounds ': ' rebs ',
' points ': ' pts ',
' assists ': ' ast '}
#rename columns in DataFrame using dictionary
df. rename (columns=some_dict, inplace= True )
#view updated DataFrame
print (df)
rebs pts ast
0 10 30 5
1 14 22 6
2 14 19 6
3 13 14 5
4 13 14 8
5 12 11 7
6 10 20 7
7 7 28 9
各列の名前は、ディクショナリで指定した値に基づいて変更されていることに注意してください。
辞書を使用してすべての列の名前を変更する必要はないことに注意してください。
たとえば、DataFrame のポイントとアシスト列のみの名前を変更する辞書を作成できます。
#define dictionary with new column names for points and assists only
some_dict = {' points ':' pts ',
' assists ': ' ast '}
#rename columns in DataFrame using dictionary
df. rename (columns=some_dict, inplace= True )
#view updated DataFrame
print (df)
rebounds pts ast
0 10 30 5
1 14 22 6
2 14 19 6
3 13 14 5
4 13 14 8
5 12 11 7
6 10 20 7
7 7 28 9
ポイントとアシストの列のみが名前変更されました。
bounces列はディクショナリに含まれていなかったため、DataFrame では名前が変更されませんでした。
追加リソース
次のチュートリアルでは、パンダで他の一般的な操作を実行する方法を説明します。
Pandas ですべての列名をリストする方法
Pandas で列を名前で並べ替える方法
Pandasで重複した列を削除する方法