Pandas: データフレームに指定した位置に行を追加する方法

この記事では、pandasデータフレームに指定した位置に行を追加する方法について説明します。この記事にはコード、結果、そして説明が含まれています。

Logo Devmath
devmath

This article has been written by ロビン・ポルト ([email protected]) and published on December 26, 2022.
The content of this article is licensed under CC BY NC 4.0 : You can freely share and adapt the content for non-commercial purposes as long as you give appropriate credit and provide a link to the license. In my case, the link to the original article is enough. Confidentiality if relevant: https://devmath.fr/page/confidentialite/

データフレームの最後に行を追加する方法について知りたい場合は、この記事を読むことができます: Pandas: データフレームの最後に行を追加する

注意: どの方法を選ぶか決める際には、時間計算量の問題も考慮してください。

提案 1

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})
line = DataFrame({'a': [10], 'b': [11], 'c': [12]}, index=[1.5])
df2 = concat([df.iloc[:2], line, df.iloc[2:]]).reset_index(drop=True)

提案 2

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})
df.loc[2.5] = 1,2,3
df = df.sort_index().reset_index(drop=True)

提案 3

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})
line = DataFrame({'a': [10], 'b': [11], 'c': [12]}, index=[1.5])
df = df.append(line, ignore_index=False)
df = df.sort_index().reset_index(drop=True)