How to Add Rows in Pandas DataFrame

There are the following methods to add rows in Pandas DataFrame.

  1. Method 1: Using the Dataframe.concat() method
  2. Method 2: Using the loc[ ] indexer
  3. Method 3: Using the insert() method

Method 1: Using the Pandas Dataframe.concat()

The concat() method can concatenate two or more DataFrames. For example, to add the row (‘new_row’, ‘value1’, ‘value2’) to the DataFrame df, use df = pd.concat([df, pd.DataFrame({‘new_row’: ‘value1’, ‘value2’: ‘value2’})])

To add a row to a DataFrame using the concat() method, you would first create a new DataFrame with the row you want to add and then concatenate the new DataFrame with the original DataFrame.

import pandas as pd

data1 = {'A': [1, 2], 'B': [3, 4]}
df1 = pd.DataFrame(data1)

data2 = {'A': [3], 'B': [5]}
df2 = pd.DataFrame(data2)

# Concatenate the DataFrames
df = pd.concat([df1, df2], ignore_index=True)

print(df)

Output

   A   B
0  1   3
1  2   4
2  3   5

Method 2: Using the loc[ ] indexer

The loc[] indexer can add a new row by specifying a new index label.

import pandas as pd

data = {'A': [1, 2], 'B': [3, 4]}
df = pd.DataFrame(data)

# Add a new row using the loc[] indexer
df.loc[len(df)] = [3, 5]

print(df)

Output

   A   B
0  1   3
1  2   4
2  3   5

Remember to set ignore_index=True in append() and concat() methods to reindex the resulting DataFrame. Otherwise, the original index values will be preserved, which may lead to duplicate index values.

Method 3: Using the index() method

The insert() method in pandas inserts a new column into a DataFrame at a specific index position. However, you can add a new row to a DataFrame by first transposing it, then using the insert() method to add a new column (which would be treated as a row after transposition), and finally, transposing it back.

import pandas as pd

data = {'A': [1, 2], 'B': [3, 4]}
df = pd.DataFrame(data)

# Transpose the DataFrame
df_T = df.T

# Insert a new row (column in the transposed DataFrame)
new_row = [5, 6]
row_position = 1 # Adjust this value to insert the row at a different position
df_T.insert(row_position, 'NewRow', new_row)

# Transpose the DataFrame back
df = df_T.T

print(df)

Output

        A  B
  0     1  3
NewRow  5  6
  1     2  4

However, using the insert() method for adding rows is not the most straightforward approach, and it might not be the most efficient one.

Instead, you can use other methods like concat() or loc[] indexer, which is more suitable for adding rows to a DataFrame.

Important note

I did not use the append() method here because of this: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.

Conclusion

The best way to add or append rows in Pandas DataFrame is to use the dataframe concat() method.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.