You can use the following basic syntax to insert a row into a a specific index position in a pandas DataFrame:
#insert row in between index position 2 and 3 df.loc[2.5] = value1, value2, value3, value4 #sort index df = df.sort_index().reset_index(drop=True)
The following example shows how to use this syntax in practice.
Example: Insert Row at Specific Index Position in Pandas
Suppose we have the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 'points': [18, 22, 19, 14, 14, 11, 20, 28], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print(df) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7 H 28 4 12
We can use the following syntax to insert a row in between index position 2 and 3:
#insert row in between index position 2 and 3
df.loc[2.5] = 'Z', 10, 5, 7
#sort index
df = df.sort_index().reset_index(drop=True)
#view updated DataFrame
print(df)
team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 Z 10 5 7
4 D 14 9 6
5 E 14 12 6
6 F 11 9 5
7 G 20 9 9
8 H 28 4 12
Notice that a row has been inserted in between the previous index position 2 and 3 with the following information:
- team: Z
- points: 10
- assists: 5
- rebounds: 7
By using the sort_index() and reset_index() functions, we were then able to reassign values to the index ranging from 0 to 8.
Note that the new row must contain the same number of values as the number of existing columns.
For example, if we attempted to insert a new row with only three values, we would receive an error:
#attempt to insert row with only three values
df.loc[2.5] = 10, 5, 7
ValueError: cannot set a row with mismatched columns
We receive a ValueError because the number of values in the new row does not match the number of existing columns in the DataFrame.
Additional Resources
The following tutorials explain how to perform other common operations in pandas:
How to Insert a Column Into a Pandas DataFrame
How to Add Rows to a Pandas DataFrame
How to Drop Rows in Pandas DataFrame Based on Condition
Does not work for all DataFrames i.e. see example below which leaves the 2.5 index at the bottom and does not properly sort and reset the index:
df1 = pd.DataFrame([[10,9,8],[7,6,5],[4,3,2],[10,9,8],[7,6,5],[4,3,2]])
df1.loc[2.5] = 100,200,300
df1.sort_index().reset_index(drop=True)
print(df1)
results in:
0 1 2
0.0 10 9 8
1.0 7 6 5
2.0 4 3 2
3.0 10 9 8
4.0 7 6 5
5.0 4 3 2
2.5 100 200 300
This is such a terrible solution.
What if I want to insert multiple row in between spots?
Then I have to deal with decimals places.
There must be a better way
Hi Aidan…To insert rows at a specific index position in a pandas DataFrame, including inserting multiple rows, you can use a combination of slicing and concatenation. Here’s a step-by-step approach to achieve this:
### Inserting a Single Row at a Specific Index
Let’s start with inserting a single row at a specific index.
“`python
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({
‘A’: [1, 2, 3],
‘B’: [4, 5, 6]
})
# New row to insert
new_row = {‘A’: 10, ‘B’: 20}
# Index at which to insert the new row
insert_at = 1
# Split the DataFrame into two parts and concatenate with the new row
df1 = df.iloc[:insert_at]
df2 = df.iloc[insert_at:]
new_df = pd.concat([df1, pd.DataFrame([new_row]), df2]).reset_index(drop=True)
print(new_df)
“`
### Inserting Multiple Rows at Specific Indices
To insert multiple rows at specific indices, you can follow a similar approach but handle the insertion for multiple rows.
“`python
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({
‘A’: [1, 2, 3],
‘B’: [4, 5, 6]
})
# New rows to insert
new_rows = [{‘A’: 10, ‘B’: 20}, {‘A’: 30, ‘B’: 40}]
# Indices at which to insert the new rows
insert_at = [1, 2]
# Sort the indices in reverse order to avoid changing positions
for i, new_row in sorted(zip(insert_at, new_rows), reverse=True):
df1 = df.iloc[:i]
df2 = df.iloc[i:]
df = pd.concat([df1, pd.DataFrame([new_row]), df2]).reset_index(drop=True)
print(df)
“`
### More Efficient Approach Using DataFrame Concatenation
For a more efficient and cleaner approach, especially when dealing with many rows, you can split the DataFrame once and use concatenation with careful indexing:
“`python
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({
‘A’: [1, 2, 3],
‘B’: [4, 5, 6]
})
# New rows to insert
new_rows = [{‘A’: 10, ‘B’: 20}, {‘A’: 30, ‘B’: 40}]
# Indices at which to insert the new rows
insert_at = [1, 2]
# Convert new rows to a DataFrame and insert NaNs for missing rows
new_rows_df = pd.DataFrame(new_rows)
full_indices = sorted(insert_at + list(range(len(df))))
# Create an empty DataFrame with the new index
new_df = pd.DataFrame(index=full_indices, columns=df.columns)
# Fill in the old DataFrame and new rows
new_df.loc[list(range(len(df)))] = df.values
new_df.loc[insert_at] = new_rows_df.values
# Reset the index and drop any missing values
new_df = new_df.reset_index(drop=True).dropna().reset_index(drop=True)
print(new_df)
“`
### Handling Decimal Places
If you need to deal with decimal places in your data, pandas provides functionality to round off values to a specific number of decimal places using the `round` method:
“`python
# Round off the DataFrame to 2 decimal places
df = df.round(2)
“`
By using the above methods, you can efficiently insert rows at specific positions in a DataFrame and handle multiple rows without complications related to indexing or decimal places.