Pandas: 特定のインデックス位置に行を挿入する方法
次の基本構文を使用して、pandas DataFrame の特定のインデックス位置に行を挿入できます。
#insert row in between index position 2 and 3 df. loc [ 2.5 ] = value1, value2, value3, value4 #sort index df = df. sort_index (). reset_index (drop= True )
次の例は、この構文を実際に使用する方法を示しています。
例: Pandas の特定のインデックス位置に行を挿入する
次のパンダ データフレームがあるとします。
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ' points ': [18, 22, 19, 14, 14, 11, 20, 28], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print (df) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7:28 4 12
次の構文を使用して、インデックス位置 2 と 3 の間に行を挿入できます。
#insert row in between index position 2 and 3
df. loc [ 2.5 ] = 'Z', 10, 5, 7
#sort index
df = df. sort_index (). reset_index (drop= True )
#view updated DataFrame
print (df)
team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 Z 10 5 7
4 D 14 9 6
5 E 14 12 6
6 F 11 9 5
7 G 20 9 9
8:28 a.m. 4:12
前のインデックス位置 2 と 3 の間に、次の情報を含む行が挿入されていることに注意してください。
- チーム:Z
- ポイント: 10
- アシスト: 5
- リバウンド: 7
sort_index()関数とreset_index()関数を使用すると、0 から 8 までの範囲のインデックスに値を再割り当てることができました。
新しい行には、既存の列の数と同じ数の値が含まれている必要があることに注意してください。
たとえば、値が 3 つだけある新しい行を挿入しようとすると、エラーが発生します。
#attempt to insert row with only three values
df. loc [ 2.5 ] = 10, 5, 7
ValueError : cannot set a row with mismatched columns
新しい行の値の数が DataFrame の既存の列の数と一致しないため、 ValueError が返されます。
追加リソース
次のチュートリアルでは、パンダで他の一般的な操作を実行する方法を説明します。
Pandas DataFrame に列を挿入する方法
Pandas DataFrame に行を追加する方法
条件に基づいて Pandas DataFrame の行を削除する方法