Skip to main content
almarefa.net

Back to all posts

How to Select First N Rows And Last Row In Python Pandas?

Published on
5 min read
How to Select First N Rows And Last Row In Python Pandas? image

Best Python Data Analysis Books to Buy in September 2025

1 Python for Data Analysis: Data Wrangling with pandas, NumPy, and Jupyter

Python for Data Analysis: Data Wrangling with pandas, NumPy, and Jupyter

BUY & SAVE
$43.99 $79.99
Save 45%
Python for Data Analysis: Data Wrangling with pandas, NumPy, and Jupyter
2 Pandas Cookbook: Practical recipes for scientific computing, time series, and exploratory data analysis using Python

Pandas Cookbook: Practical recipes for scientific computing, time series, and exploratory data analysis using Python

BUY & SAVE
$35.74 $49.99
Save 29%
Pandas Cookbook: Practical recipes for scientific computing, time series, and exploratory data analysis using Python
3 Effective Pandas: Patterns for Data Manipulation (Treading on Python)

Effective Pandas: Patterns for Data Manipulation (Treading on Python)

BUY & SAVE
$48.95
Effective Pandas: Patterns for Data Manipulation (Treading on Python)
4 Pandas Workout: 200 exercises to make you a stronger data analyst

Pandas Workout: 200 exercises to make you a stronger data analyst

BUY & SAVE
$49.44 $59.99
Save 18%
Pandas Workout: 200 exercises to make you a stronger data analyst
5 Hands-On Data Analysis with Pandas: A Python data science handbook for data collection, wrangling, analysis, and visualization

Hands-On Data Analysis with Pandas: A Python data science handbook for data collection, wrangling, analysis, and visualization

BUY & SAVE
$64.99
Hands-On Data Analysis with Pandas: A Python data science handbook for data collection, wrangling, analysis, and visualization
6 Effective Pandas 2: Opinionated Patterns for Data Manipulation (Treading on Python)

Effective Pandas 2: Opinionated Patterns for Data Manipulation (Treading on Python)

BUY & SAVE
$54.00
Effective Pandas 2: Opinionated Patterns for Data Manipulation (Treading on Python)
7 Pandas for Everyone: Python Data Analysis (Addison-Wesley Data & Analytics Series)

Pandas for Everyone: Python Data Analysis (Addison-Wesley Data & Analytics Series)

BUY & SAVE
$43.51 $49.99
Save 13%
Pandas for Everyone: Python Data Analysis (Addison-Wesley Data & Analytics Series)
8 Python Data Cleaning Cookbook: Prepare your data for analysis with pandas, NumPy, Matplotlib, scikit-learn, and OpenAI

Python Data Cleaning Cookbook: Prepare your data for analysis with pandas, NumPy, Matplotlib, scikit-learn, and OpenAI

BUY & SAVE
$37.93 $49.99
Save 24%
Python Data Cleaning Cookbook: Prepare your data for analysis with pandas, NumPy, Matplotlib, scikit-learn, and OpenAI
9 Pandas in Action

Pandas in Action

BUY & SAVE
$49.91 $59.99
Save 17%
Pandas in Action
10 Learning the Pandas Library: Python Tools for Data Munging, Analysis, and Visual

Learning the Pandas Library: Python Tools for Data Munging, Analysis, and Visual

BUY & SAVE
$19.99
Learning the Pandas Library: Python Tools for Data Munging, Analysis, and Visual
+
ONE MORE?

To select the first n rows and the last row in Python pandas, you can use the following methods:

  1. Using the .head() and .tail() methods: .head(n): Returns the first n rows of the dataframe. .tail(1): Returns the last row of the dataframe. Example: first_n_rows = df.head(n) last_row = df.tail(1)
  2. Using slicing: You can use slicing to select a range of rows from the dataframe. Example: first_n_rows = df[:n] last_row = df[-1:]
  3. Using the .iloc[] indexer: .iloc[] allows you to select rows by integer position. Example: first_n_rows = df.iloc[:n] last_row = df.iloc[-1:]

These methods will help you select the desired rows from a pandas dataframe.

What is the difference between loc and iloc in Pandas?

The main difference between loc and iloc in Pandas is the way they are used to index data:

  1. loc: It is used for label-based indexing. It allows you to access data based on the indexes (labels) of rows and columns. The syntax for using loc is df.loc[row_indexer, column_indexer]. The row_indexer and column_indexer can be single labels, lists of labels, or boolean arrays.
  2. iloc: It is used for integer-based indexing. It allows you to access data based on the integer position of rows and columns. The syntax for using iloc is df.iloc[row_indexer, column_indexer]. The row_indexer and column_indexer can be single integers, lists of integers, or boolean arrays.

In summary, loc uses labels (indexes) to access data, while iloc uses integer positions.

How to count the number of occurrences of a value in a column?

To count the number of occurrences of a value in a column, you can use the COUNTIF function in Excel. Here's how to do it:

  1. Select an empty cell where you want the count result to appear.
  2. Type the following formula: =COUNTIF(range, criteria) Replace "range" with the range of the column where you want to count the occurrences. Replace "criteria" with the value you want to count.
  3. Press Enter to see the count result.

For example, let's say you have a column of numbers in cells A1 to A10, and you want to count how many times the value "5" appears in that column. You would use the formula: =COUNTIF(A1:A10, 5)

After pressing Enter, the cell will display the count of occurrences of the value "5" in the column.

How to rename columns in a DataFrame?

To rename columns in a DataFrame, you can use the rename() method. Here are the steps to rename columns in a DataFrame:

  1. Import the required libraries:

import pandas as pd

  1. Create a DataFrame:

df = pd.DataFrame({'Column1': [1, 2, 3], 'Column2': [4, 5, 6]})

  1. Use the rename() method to rename columns (pass a dictionary with old column names and new column names as keys and values):

df.rename(columns={'Column1': 'NewColumn1', 'Column2': 'NewColumn2'}, inplace=True)

Note: Setting inplace=True will modify the DataFrame in place, without creating a new DataFrame. If you omit inplace=True, a new DataFrame with renamed columns will be returned.

Let's see an example to rename columns in a DataFrame:

import pandas as pd

Create a DataFrame

df = pd.DataFrame({'Name': ['John', 'Alice', 'Bob'], 'Age': [25, 30, 35], 'City': ['New York', 'London', 'Paris']})

Rename columns

df.rename(columns={'Name': 'First Name', 'Age': 'Age (years)', 'City': 'Current City'}, inplace=True)

Display the updated DataFrame

print(df)

Output:

First Name Age (years) Current City 0 John 25 New York 1 Alice 30 London 2 Bob 35 Paris

As you can see, the columns of the DataFrame have been renamed according to the given dictionary.

What is the dtype of a column in Pandas?

The dtype of a column in Pandas refers to the data type of the values in that column. Pandas supports various data types such as integers, floats, strings, booleans, datetime objects, etc. The dtype can be accessed using the dtype attribute for a specific column or by calling the dtypes attribute for the entire DataFrame.

What is the use of the describe() function in Pandas?

The describe() function in pandas is used to generate descriptive statistics of a DataFrame or Series. It provides a summary of the central tendency, dispersion, and shape of the distribution of a dataset.

The output of describe() includes count (number of non-null values), mean, standard deviation, minimum value, 25th, 50th, and 75th percentiles (quartiles), and maximum value. It also provides information about the data type and memory usage of each column.

By default, only numerical columns are included in the output. However, by specifying the include parameter, you can also include other data types such as object or categorical columns. Additionally, you can include or exclude specific percentiles or summary statistics using the percentiles and exclude parameters, respectively.

Overall, the describe() function is useful for getting a quick overview and understanding of the basic statistics and distribution of the data in a DataFrame or Series.