Получить количество строк и количество столбцов в Pandas Dataframe
Pandas предоставляет аналитикам данных множество предопределенных функций для получения количества строк и столбцов во фрейме данных. В этой статье мы узнаем о синтаксисе и реализации нескольких таких функций.
Метод 1. Использование метода df.axes ()
axes() method in pandas allows to get the number of rows and columns in a go. It accepts the argument ‘0’ for rows and ‘1’ for columns.
Syntax: df.axes[0 or 1]
Parameters:
0: for number of Rows
1: for number of columns
Пример:
# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { "Name" : ["Ankit", "Aishwarya", "Shaurya", "Shivangi"], "Age" : [23, 21, 22, 21], "University" : ["BHU", "JNU", "DU", "BHU"],} # creating a Dataframe object df = pd.DataFrame(details, columns = ["Name", "Age", "University"], index = ["a", "b", "c", "d"]) # Get the number of rows and columnsrows = len(df.axes[0])cols = len(df.axes[1]) # Print the number of rows and columnsprint("Number of Rows: " + str(rows))print("Number of Columns: " + str(cols)) |
Выход:
Количество рядов: 4 Количество столбцов: 3
Метод 2: использование метода df.info ()
df.info() method provides all the information about the data frame, including the number of rows and columns.
Синтаксис:
df.info
Example:
# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { "Name" : ["Ankit", "Aishwarya", "Shaurya", "Shivangi"], "Age" : [23, 21, 22, 21], "University" : ["BHU", "JNU", "DU", "BHU"],} # creating a Dataframe object df = pd.DataFrame(details, columns = ["Name", "Age", "University"], index = ["a", "b", "c", "d"]) # Get the info of data framedf.info() |
Выход:

Здесь, в приведенном выше коде, значение в индексе дает количество строк, а значение в столбцах данных дает количество столбцов.
Метод 3: использование метода len ()
len() method is used to get the number of rows and number of columns individually.
Синтаксис:
len (df) а также len (df.columns)
Example 1: Get the number of rows
# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { "Name" : ["Ankit", "Aishwarya", "Shaurya", "Shivangi"], "Age" : [23, 21, 22, 21], "University" : ["BHU", "JNU", "DU", "BHU"],} # creating a Dataframe object df = pd.DataFrame(details, columns = ["Name", "Age", "University"], index = ["a", "b", "c", "d"]) # Get the number of rowsprint("Number of Rows:", len(df)) |
Выход:
Количество рядов: 4
Example 2: Get the number of columns
# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { "Name" : ["Ankit", "Aishwarya", "Shaurya", "Shivangi"], "Age" : [23, 21, 22, 21], "University" : ["BHU", "JNU", "DU", "BHU"],} # creating a Dataframe object df = pd.DataFrame(details, columns = ["Name", "Age", "University"], index = ["a", "b", "c", "d"]) # Get the number of columnsprint("Number of Columns:", len(df.columns)) |
Выход:
Количество столбцов: 3
Метод 4: Использование метода df.shape ()
df.shape() method returns the number of rows and columns in the form of a tuple.
Example:
# import pandas libraryimport pandas as pd # dictionary with list object in valuesdetails = { "Name" : ["Ankit", "Aishwarya", "Shaurya", "Shivangi"], "Age" : [23, 21, 22, 21], "University" : ["BHU", "JNU", "DU", "BHU"],} # creating a Dataframe object df = pd.DataFrame(details, columns = ["Name", "Age", "University"], index = ["a", "b", "c", "d"]) # Get the number of Rows and columnsdf.shape |
Выход:
(4, 3)
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.