Pandas – это библиотека Python с открытым исходным кодом для обработки и анализа данных. Он предоставляет мощный и гибкий набор инструментов для работы со структурированными данными, такими как табличные данные, временные ряды и матричные данные. Он добавляет дополнительные функции, упрощающие работу с табличными данными, такие как индексация, фильтрация, сводка и группировка.

Pandas предоставляет две основные структуры данных: Series и DataFrame. Серия — это одномерный объект, похожий на массив, который может содержать данные любого типа, а DataFrame — это двумерная табличная структура, состоящая из строк и столбцов.

Если вы никогда раньше не использовали библиотеку pandas, вы можете установить pandas с помощью этого фрагмента кода.

pip install pandas

Сначала мы импортируем библиотеку pandas

# Import Pandas Library
import pandas as pd

Теперь давайте создадим DataFrames

df = pd.read_csv("data.csv")

Давайте немного узнаем о данных

  • Column: представляет имя каждого столбца в таблице или фрейме данных.
  • Non-Null Count: представляет количество ненулевых значений в каждом столбце. Нулевое значение представляет отсутствующее или неизвестное значение в наборе данных.
  • Dtype: представляет тип данных каждого столбца. Тип данных определяет тип значений, которые могут храниться в каждом столбце, например целое число, число с плавающей запятой, логическое значение или строка.

Давайте рассмотрим информацию DataFrame.

# df.head() is a Pandas DataFrame method that is used to display the first few rows of a DataFrame. 
# By default, it displays the first 5 rows, but you can specify a different number of rows by passing an integer argument to the method.
df.head() 

# df.tail() is a Pandas DataFrame method that is used to display the last few rows of a DataFrame. 
# By default, it displays the last 5 rows, but you can specify a different number of rows by passing an integer argument to the method.
df.tail()

# df.columns is a Pandas DataFrame attribute that returns a list of the column names in the DataFrame.
df.columns

# len(df) returns the number of rows in a Pandas DataFrame df.
len(df)

# output = 569
# df.shape is a Python function that returns the dimensions of a Pandas DataFrame df as a tuple. 
# The first element of the tuple is the number of rows in the DataFrame, and the second element is the number of columns in the DataFrame.
df.shape

# Output : (569, 33)
# With this code we renamed only the first 3 columns of Pandas DataFrame df.
df.columns.values[:3] = ['IntroPandas1', 'IntroPandas2', 'IntroPandas3']

Фильтрация столбцов и строк

# To select a specific column(s) of a DataFrame, you can use the indexing operator [] with the column name(s) enclosed in quotes.
df_filtered = df['column_name']

# To select multiple columns, you can pass a list of column names inside the indexing operator. 
df_filtered = df[['column_name_1', 'column_name_2']]

# Specifically, it selects only the rows where the value in the 'column_name' column is greater than 10, and creates a new DataFrame df_filtered that contains only these rows.
df_filtered = df[df['column_name'] > 10]

# Specifically, it selects only the rows where the value in the 'column_name_1' column is greater than 10 AND the value in the 'column_name_2' column is less than 5, and creates a new DataFrame df_filtered that contains only these rows.
df_filtered = df[(df['column_name_1'] > 10) & (df['column_name_2'] < 5)

Отсутствующие значения

# Delete rows with missing values
# Drops all rows in a Pandas DataFrame df that have at least one missing value, and modifies df in place (i.e., it does not create a new DataFrame). 
# The axis=0 parameter specifies that we want to drop rows, and inplace=True specifies that we want to modify the original DataFrame instead of creating a new one.
df.dropna(axis=0, inplace=True)

# Delete columns with missing values
# Drops all columns in a Pandas DataFrame df that have at least one missing value, and modifies df in place. 
# The axis=1 parameter specifies that we want to drop columns.
df.dropna(axis=1, inplace=True)

# Fill missing values with a specific value
# Fills all missing values in a Pandas DataFrame df with a specific value (in this case, 0), and modifies df in place. 
# The value=0 parameter specifies the value we want to use for filling missing values.
df.fillna(value=0, inplace=True)

# Check for missing values
# Returns the number of missing values in each column of a Pandas DataFrame df.
# The isnull() method returns a boolean DataFrame that has the same shape as df, where each element is True if the corresponding element in df is missing (NaN), and False otherwise.
# The sum() method is then called on this boolean DataFrame to count the number of True values (i.e., the number of missing values) in each column.
df.isnull().sum()

Удалить столбцы и строки

# Drop columns by name
df.drop(['column_name_1', 'column_name_2'], axis=1, inplace=True)

Удаляет два столбца, «column_name_1» и «column_name_2», из Pandas DataFrame df и изменяет df на месте.

# [‘column_name_1’, ‘column_name_2’]: список имен столбцов, которые мы хотим удалить из DataFrame.

# axis=1: указывает, что мы хотим удалить столбцы (в отличие от строк, которые были бы axis=0).

# inplace=True: указывает, что мы хотим изменить исходный фрейм данных вместо создания нового.

# При вызове этого кода два указанных столбца удаляются из df, а измененный DataFrame возвращается с тем же именем переменной df.

# Drop columns by index
df.drop(df.columns[[0, 2]], axis=1, inplace=True)

# Drop rows by index
df.drop([0, 2, 4], axis=0, inplace=True)

В другой своей статье я расскажу о библиотеках numpy и matplotlib.

Я хотел бы поделиться с вами наглядным примером набора данных, который мы использовали выше с matplotlib, и до встречи в следующих статьях.

import matplotlib.pyplot as plt
# scatter plot
plt.scatter(M.radius_mean,M.texture_mean,color="red",label="kotu",alpha =0.3)
plt.scatter(B.radius_mean,B.texture_mean,color="green",label="iyi",alpha =0.3)
plt.xlabel("radius_mean")
plt.ylabel("texture_mean")
plt.legend()
plt.show()