Подсчитать количество столбцов фрейма данных Pandas
Давайте обсудим, как подсчитать количество столбцов в фрейме данных Pandas. Давайте сначала создадим фрейм данных.
Example:
Python3
# Import Required Librariesimport pandas as pdimport numpy as np # Create a dictionary for the dataframedict = {"Name": ["Sukritin", "Sumit Tyagi", "Akriti Goel", "Sanskriti", "Abhishek Jain"], "Age": [22, 20, np.inf, -np.inf, 22], "Marks": [90, 84, 33, 87, 82]} # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframedf |
Выход:

Метод 1: использование свойства shape
Shape property returns the tuple representing the shape of the DataFrame. The first index consists of the number of rows and the second index consist of the number of columns.
Python3
# Getting shape of the dfshape = df.shape # Printing Number of columnsprint("Number of columns :", shape[1]) |
Выход:

Метод 2: использование свойства columns
Свойство columns в Pandas DataFrame возвращает список столбцов и, вычисляя длину списка столбцов, мы можем получить количество столбцов в df.
Python3
# Getting the list of columnscol = df.columns # Printing Number of columnsprint("Number of columns :", len(col)) |
Выход:

Метод 3: приведение DataFrame в список
Like the columns property, typecasting DataFrame to the list returns the list of the name of the columns.
Python3
# Typecasting df to listdf_list = list(df) # Printing Number of columnsprint("Number of columns :", len(df_list)) |
Выход:

Метод 4: использование метода info () DataFrame
This methods prints a concise summary of the DataFrame. info() method prints information about the DataFrame including dtypes of columns and index, memory usage, number of columns, etc.
Python3
# Printing info of dfdf.info() |
Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.