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.

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)