Pandas: Ajouter une ligne à une position donnée dans un dataframe

Cet article décrit comment ajouter une ligne à un dataframe pandas à une position donnée. Le code, le résultat et l'explication sont fournis dans cet article.

Logo Devmath
devmath

This article has been written by Robin Pourtaud ([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/

Si vous souhaitez ajouter une ligne à la fin d’un dataframe, vous pouvez utiliser la méthode append() de pandas. Pour plus d’informations, vous pouvez consulter cet article: Pandas: Ajouter une ligne à la fin d’un dataframe

Attention : prenez en compte la complexité temporelle de votre code.

Proposition 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)

Proposition 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)

Proposition 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)