A DataFrame is given and the task is to remove the first row from it. For example, consider the following DataFrame:
Input: A B
0 1 2
1 3 4Output: A B
1 3 4
Let's explore different methods to drop first row.
Using iloc for Index-Based Selection
iloc is used to select data based on integer (position-based) indexing in a DataFrame. It allows to access rows and columns using their index positions. To drop the first row using iloc, select all rows starting from index 1:
import pandas as pd
d = pd.DataFrame({'name': ['Mike', 'Kate', 'Nancy', 'Emilia'],
'age': [21, 22, 21, 22]})
print(d.iloc[1:])
Output
name age 1 Kate 22 2 Nancy 21 3 Emilia 22
Explanation:
- slice [1:] selects rows starting from index 1.
- All remaining rows are selected and printed.
Using drop() Method
In this method, the index of the row (typically 0) is specified and the drop() method is used with the index parameter set to 0. To modify the original DataFrame directly, the inplace=True argument is used.
import pandas as pd
d = pd.DataFrame({'name': ['Mike', 'Kate', 'Nancy', 'Emilia'],
'age': [21, 22, 21, 22]})
d.drop(index=d.index[0], axis=0, inplace=True)
print(d)
Output
name age 1 Kate 22 2 Nancy 21 3 Emilia 22
Explanation:
- First row is selected using data.index[0].
- axis=0 specifies that a row is being removed.
- inplace=True argument applies the change directly to the original DataFrame.
Using loc
loc is used to drop the first row by selecting data based on index labels instead of positions. By starting the selection from the second label onward, it excludes the first row from the DataFrame.
import pandas as pd
d = pd.DataFrame({'name': ['Mike', 'Kate', 'Nancy', 'Emilia'],
'age': [21, 22, 21, 22]})
d.index = [10, 20, 30, 40]
print(d.loc[20:])
Output
name age 20 Kate 22 30 Nancy 21 40 Emilia 22
Explanation:
- index is changed to custom labels [10, 20, 30, 40].
- loc[20:] selects rows starting from label 20.
- iloc[1:] selects rows starting from position 1 (second row).
Using tail() Function
The tail() function is used to drop the first row by selecting all rows except the first based on count. By taking the last n-1 rows, it excludes the first row from the DataFrame.
import pandas as pd
d = pd.DataFrame({'name': [ 'Mike', 'Kate', 'Nancy', 'Emilia'],
'age': [21, 22, 21, 22]})
d = d.tail(d.shape[0] - 1)
print(d)
Output
name age 1 Kate 22 2 Nancy 21 3 Emilia 22
Explanation:
- shape[0] gives the total number of rows.
- tail(d.shape[0] - 1) selects all rows except the first.