How to Add a Row to a Pandas DataFrame


How can we append a single row to a Pandas DataFrame?

Suppose we have a DataFrame df with columns name and age.

Append row using loc()

We can add a single row to a DataFrame using loc().

The loc() function will allow us to assign a new row to an index value.

We can obtain the last index using len(df.index).

df.loc[len(df.index)] = ['John', 23] 

Append row using append()

We can also use append() to achieve the same functionality.

row = {'name': 'John', 'age': 23}
df = df.append(row, ignore_index = True)

Append row(s) using concat()

If the row exists in another DataFrame, we can use concat() to append the second DataFrame to the first.

df2 = pd.DataFrame({'name': ['John'], 'age': [23]})
df = pd.concat([df, df2], ignore_index = True)
df.reset_index()