この記事では、reset_index() と concat() 関数を使用して DataFrame オブジェクトのインデックスをリセットする方法について説明します。
また、pandas DataFrameのインデックスをリセットする必要がある様々なシナリオについても説明します。
こちらもお読みください。
pandasのreset_index()関数のシンタックス
Python では、pandas DataFrame クラスの reset_index() 関数を使用して、pandas DataFrame オブジェクトのインデックスをリセットすることができます。
reset_index()関数は、pandas DataFrame のインデックスをデフォルトで Pandas のデフォルトインデックスにリセットし、新しいインデックスを持つ pandas DataFrame オブジェクトかNone値を返します。
もし、Pandas DataFrame が複数のレベルのインデックスを持っている場合、この関数は1つ以上のレベルを削除することができます。
それでは、reset_index()` 関数のシンタックスを簡単に理解しましょう。
# Syntax of the reset_index() function in pandasDataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')
|
ほとんどの場合、drop と inplace の2つのパラメータしか使用しませんが、残りのパラメータはあまり使用しません。
- drop: drop: DataFrameのカラムにインデックスを挿入しないようにします。pandasのDataFrameのインデックスをデフォルトの整数インデックスにリセットします。このパラメータは、TrueまたはFalseのブール値をとりますが、デフォルトではFalseです。
- インプレース。inplace: 新しい pandas DataFrame オブジェクトを作成するのではなく、DataFrame のインデックスをリセットする処理を行います。また、デフォルトでは False である boolean 値を受け取ります。
この記事もチェック:PythonのPandasでブールインデックス参照を実装する方法
Reset Index of a DataFrame using the reset_index() function
Pythonでは、以下のようなシナリオでpandas DataFrameオブジェクトのインデックスをリセットする必要があります。
1. DataFrameに行が追加された場合
元のDataFrameオブジェクトに数行の行を追加すると、新しい行のインデックスは0から始まります。
ここで、reset_index()関数を適用してDataFrameのインデックスをリセットすることができます。
以下のデモを見てください。
# Case-1# When some rows are inserted in the DataFrame# Import pandasimport pandas as pd
# Create a DataFrame object # Using DataFrame() functiondf1 = pd.DataFrame({"Date": ['11/05/21', '15/06/21', '17/07/21'],
"Item": ['Television', 'Speaker', 'Monitor'],
"Sales": [200, 300, 115]})
print("Original DataFrame:)
print(df1)
# Create an another DataFramedf2 = pd.DataFrame({"Date": ['04/05/20', '29/07/20', '30/08/20'],
"Item": ['Mixer', 'Bulb', 'Cooler'],
"Sales": [803, 178, 157]})
# Add the rows of DataFrame (df2) to the DataFrame (df1)# Using the concat() functiondf = pd.concat([df1, df2])
print(")
print(df)
# Reset the index of the final DataFrame # Using reset_index() functiondf.reset_index(drop = True, inplace = True)
print(")
print(df)
|
結果は以下の通りです。
出力:
Original DataFrame: Date Item Sales
0 11/05/21 Television 2001 15/06/21 Speaker 3002 17/07/21 Monitor 115DataFrame after inserting some rows: Date Item Sales
0 11/05/21 Television 2001 15/06/21 Speaker 3002 17/07/21 Monitor 1150 04/05/20 Mixer 8031 29/07/20 Bulb 1782 30/08/20 Cooler 157DataFrame after the resetting the index: Date Item Sales
0 11/05/21 Television 2001 15/06/21 Speaker 3002 17/07/21 Monitor 1153 04/05/20 Mixer 8034 29/07/20 Bulb 1785 30/08/20 Cooler 157 |
2. DataFrame内の行が削除された場合
この場合、まずインデックスが乱れた元のDataFrameオブジェクトから、選択したいくつかの行をドロップ/デリートします。
その後、最終的なDataFrameに reset_index() 関数を適用して、値を再集計します。
それでは、このケースを実装するためのPythonコードを見てみましょう。
# Case-2# When few rows from DataFrame are deleted# Import pandas Python moduleimport pandas as pd
# Create a DataFrame object # Using DataFrame() functiondf = pd.DataFrame({"Date": ['11/05/21', '15/06/21', '17/07/21', '19/11/20', '21/12/20'],
"Item": ['Television', 'Speaker', 'Desktop', 'Dish-Washer', 'Mobile'],
"Sales": [200, 300, 115, 303, 130]})
print("Original DataFrame:)
print(df)
# Delete few rows of the DataFrame (df)# Using drop() function df = df.drop(labels = [0, 3], axis = 0)
print(")
print(df)
# Reset the index of the final DataFrame # Using reset_index() functiondf.reset_index(drop = True, inplace = True)
print(")
print(df)
|
結果は以下の通りです。
Original DataFrame: Date Item Sales
0 11/05/21 Television 2001 15/06/21 Speaker 3002 17/07/21 Desktop 1153 19/11/20 Dish-Washer 3034 21/12/20 Mobile 130DataFrame after deleting few rows: Date Item Sales
1 15/06/21 Speaker 3002 17/07/21 Desktop 1154 21/12/20 Mobile 130DataFrame after the resetting the index: Date Item Sales
0 15/06/21 Speaker 3001 17/07/21 Desktop 1152 21/12/20 Mobile 130 |
3. データフレーム内で行がソートされている場合
この場合、まず元のDataFrameオブジェクトの行を1つまたは複数の列に従ってソートし、最終的なDataFrameオブジェクトに reset_index() 関数を適用します。
それでは、Pythonコードでこのケースを実装する方法を見てみましょう。
# Case-3# When rows of the DataFrame are sorted# Import pandas Python moduleimport pandas as pd
# Create a DataFrame object # Using DataFrame() functiondf = pd.DataFrame({"Date": ['11/05/21', '15/06/21', '17/07/21', '19/11/20', '21/12/20'],
"Item": ['Television', 'Speaker', 'Desktop', 'Dish-Washer', 'Mobile'],
"Sales": [200, 300, 115, 303, 130]})
print("Original DataFrame:)
print(df)
# Sort the rows of the DataFrame (df)# Using sort_values() functiondf.sort_values(by = "Sales", inplace = True)
print(")
print(df)
# Reset the index of the final DataFrame # Using reset_index() functiondf.reset_index(drop = True, inplace = True)
print(")
print(df)
|
結果は以下の通りです。
Original DataFrame: Date Item Sales
0 11/05/21 Television 2001 15/06/21 Speaker 3002 17/07/21 Desktop 1153 19/11/20 Dish-Washer 3034 21/12/20 Mobile 130DataFrame after sorting the rows by Sales: Date Item Sales
2 17/07/21 Desktop 1154 21/12/20 Mobile 1300 11/05/21 Television 2001 15/06/21 Speaker 3003 19/11/20 Dish-Washer 303DataFrame after the resetting the index: Date Item Sales
0 17/07/21 Desktop 1151 21/12/20 Mobile 1302 11/05/21 Television 2003 15/06/21 Speaker 3004 19/11/20 Dish-Washer 303 |
4. 2つのデータフレームを追記した場合
これもよくあるケースですが、pandasのDataFrameオブジェクトのインデックスをリセットする必要があります。
この場合、まず元のDataFrameオブジェクトに別のDataFrameオブジェクトを追加し、最終的に結合されたDataFrameオブジェクトに reset_index() 関数を適用しています。
では、このケースを実装するためのPythonコードを書いてみましょう。
# Case-4# When two DataFrames are appended# Import pandas Python moduleimport pandas as pd
# Create a DataFrame object # Using DataFrame() functiondf1 = pd.DataFrame({"Date": ['11/05/21', '15/06/21', '17/07/21'],
"Item": ['Television', 'Speaker', 'Desktop'],
"Sales": [200, 300, 115]})
print("Original DataFrame:)
print(df1)
# Create a new DataFramedf2 = pd.DataFrame({"Date": ['19/11/20', '21/12/20'],
"Item": ['Dish-Washer', 'Mobile'],
"Sales": [403, 130]})
# Append the new DataFrame (df1) to the previous one (df2)df = df1.append(df2)
print(")
print(df)
# Reset the index of the final DataFrame # Using reset_index() functiondf.reset_index(drop = True, inplace = True)
print(")
print(df)
|
結果は以下の通りです。
Original DataFrame: Date Item Sales
0 11/05/21 Television 2001 15/06/21 Speaker 3002 17/07/21 Desktop 115DataFrame after appending the new DataFrame: Date Item Sales
0 11/05/21 Television 2001 15/06/21 Speaker 3002 17/07/21 Desktop 1150 19/11/20 Dish-Washer 4031 21/12/20 Mobile 130DataFrame after the resetting the index: Date Item Sales
0 11/05/21 Television 2001 15/06/21 Speaker 3002 17/07/21 Desktop 1153 19/11/20 Dish-Washer 4034 21/12/20 Mobile 130 |
concat() 関数を使ってデータフレームのインデックスをリセットする
Python では、pandas の concat() 関数と ignor_index パラメータを使用して、pandas DataFrame オブジェクトのインデックスをリセットすることも可能です。
デフォルトでは、 ignore_index パラメータの値は False になっています。
DataFrameのインデックスをリセットするためには、その値をTrueに設定する必要があります。
それでは、Pythonのコードで実装してみましょう。
# Reset the index of DataFrame using concat() function# Import pandas Python moduleimport pandas as pd
# Create a DataFrame object # Using DataFrame() functiondf1 = pd.DataFrame({"Date": ['11/05/21', '15/06/21', '17/07/21'],
"Item": ['Television', 'Speaker', 'Desktop'],
"Sales": [200, 300, 115]})
print("Original DataFrame:)
print(df1)
# Create a new DataFramedf2 = pd.DataFrame({"Date": ['14/10/20', '19/11/20', '21/12/20'],
"Item": ['Oven', 'Toaster', 'Fan'],
"Sales": [803, 178, 157]})
# Concat the new DataFrame (df2) with the prevous one (df1)# And reset the index of the DataFrame# Using the concat() function with ignor_index parameterdf = pd.concat([df1, df2], ignore_index = True)
print(")
print(df)
|
結果は以下の通りです。
Original DataFrame: Date Item Sales
0 11/05/21 Television 2001 15/06/21 Speaker 3002 17/07/21 Desktop 115DataFrame after concatenation and index reset: Date Item Sales
0 11/05/21 Television 2001 15/06/21 Speaker 3002 17/07/21 Desktop 1153 14/10/20 Oven 8034 19/11/20 Toaster 1785 21/12/20 Fan 157 |
まとめ
この記事では、pandasの reset_index() 関数を使用して、変更したpandas DataFrameオブジェクトのインデックスをリセットする方法とタイミングを学びました。
このチュートリアルで説明したことを理解し、自分自身でこれらのDataFrameの操作を行うことができるようになれば幸いです。
Pythonに関連するこのような有益な記事をもっと見るために私たちと一緒にご滞在をありがとうございます。