Подсчитать количество столбцов фрейма данных Pandas

Опубликовано: 27 Марта, 2022

Давайте обсудим, как подсчитать количество столбцов в фрейме данных Pandas. Давайте сначала создадим фрейм данных.

Example:

Python3

# Import Required Libraries
import pandas as pd
import numpy as np
  
# Create a dictionary for the dataframe
dict = {"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 Dataframe
df = pd.DataFrame(dict)
  
# Print Dataframe
df

Выход:

Метод 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 df
shape = df.shape
  
# Printing Number of columns
print("Number of columns :", shape[1])

Выход:

Метод 2: использование свойства columns

Свойство columns в Pandas DataFrame возвращает список столбцов и, вычисляя длину списка столбцов, мы можем получить количество столбцов в df.

Python3

# Getting the list of columns
col = df.columns
  
# Printing Number of columns
print("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 list
df_list = list(df)
  
# Printing Number of columns
print("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 df
df.info()

Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

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