Pandas: Add a line to a given position in a dataframe

This article describes how to add a line to a pandas dataframe at a given position. The code, the result and the explanation are provided in this 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/

If you want to know how to add a line to the end of a dataframe, you can read this article: Pandas: Add a line to the end of a dataframe

Caution: Don’t forget to consider time complexity problems while choosing wich method suits you best.

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)