want to add a row at the bottom of the DataFrame. We are using loc[] to add a row at the bottom of the pandas DataFrame. Please note that we need to use loc[] and not iloc[]. iloc[] cannot add rows to a DataFrame.
How to add a row at the top of a pandas DataFrame using Python?
We can use the following Python code to add a row at the top of a pandas DataFrame using Python.
import pandas
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
df = pandas.DataFrame(list1)
print("df before adding row: \n", df)
df.loc[-1] = [13, 14, 15]
df.index = df.index + 1
df = df.sort_index(axis=0)
print("df after adding row: \n", df)
The output of the above program will be:
df before adding row:
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
df after adding row:
0 1 2
0 13 14 15
1 1 2 3
2 4 5 6
3 7 8 9
Here, we are using df.loc[-1] to add a row at index -1. After that we are incrementing the indexes and sorting the rows as per the indexes. As a result, the new row gets added at the top of the pandas DataFrame.
How to insert a row at a specific index of a pandas DataFrame using Python?
Let’s say we have the following DataFrame:
0 1 2 0 1 2 3 1 4 5 6 2 7 8 9
We want to insert a row in the middle of a DataFrame, such that the DataFrame becomes like this:








































0 Comments