MII/mai/lab1.ipynb
2024-12-14 15:49:48 +04:00

302 KiB
Raw Permalink Blame History

Лабораторная работа 1

Вариант - 11 Датасет - цены на бриллианты

Загрузка и сохранение данных

In [17]:
import pandas as pd

df = pd.read_csv("data/Diamonds Prices2022.csv")
df.to_csv("data/Diamonds Prices2022 updated.csv", index=False)

Получение сведений о датафрейме с данными

  1. Общая информация о датафрейме
In [2]:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 53943 entries, 0 to 53942
Data columns (total 11 columns):
 #   Column   Non-Null Count  Dtype  
---  ------   --------------  -----  
 0   id       53943 non-null  int64  
 1   carat    53943 non-null  float64
 2   cut      53943 non-null  object 
 3   color    53943 non-null  object 
 4   clarity  53943 non-null  object 
 5   depth    53943 non-null  float64
 6   table    53943 non-null  float64
 7   price    53943 non-null  int64  
 8   x        53943 non-null  float64
 9   y        53943 non-null  float64
 10  z        53943 non-null  float64
dtypes: float64(6), int64(2), object(3)
memory usage: 4.5+ MB
  1. Статистическая информация
In [3]:
df.describe()
Out[3]:
id carat depth table price x y z
count 53943.000000 53943.000000 53943.000000 53943.000000 53943.000000 53943.000000 53943.000000 53943.000000
mean 26972.000000 0.797935 61.749322 57.457251 3932.734294 5.731158 5.734526 3.538730
std 15572.147122 0.473999 1.432626 2.234549 3989.338447 1.121730 1.142103 0.705679
min 1.000000 0.200000 43.000000 43.000000 326.000000 0.000000 0.000000 0.000000
25% 13486.500000 0.400000 61.000000 56.000000 950.000000 4.710000 4.720000 2.910000
50% 26972.000000 0.700000 61.800000 57.000000 2401.000000 5.700000 5.710000 3.530000
75% 40457.500000 1.040000 62.500000 59.000000 5324.000000 6.540000 6.540000 4.040000
max 53943.000000 5.010000 79.000000 95.000000 18823.000000 10.740000 58.900000 31.800000

Получение сведений о колонках датафрейма

  1. Названия колонок
In [4]:
df.columns
Out[4]:
Index(['id', 'carat', 'cut', 'color', 'clarity', 'depth', 'table', 'price',
       'x', 'y', 'z'],
      dtype='object')

Вывод отдельных строк и столбцов

  1. Столбец "carat"
In [5]:
df[["carat"]]
Out[5]:
carat
0 0.23
1 0.21
2 0.23
3 0.29
4 0.31
... ...
53938 0.86
53939 0.75
53940 0.71
53941 0.71
53942 0.70

53943 rows × 1 columns

  1. Несколько столбцокв
In [6]:
df[["id", "cut"]]
Out[6]:
id cut
0 1 Ideal
1 2 Premium
2 3 Good
3 4 Premium
4 5 Good
... ... ...
53938 53939 Premium
53939 53940 Ideal
53940 53941 Premium
53941 53942 Premium
53942 53943 Very Good

53943 rows × 2 columns

  1. Первая строка
In [7]:
df.iloc[[0]]
Out[7]:
id carat cut color clarity depth table price x y z
0 1 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43
  1. Вывод по условию
In [8]:
df[df["price"] > 400]
Out[8]:
id carat cut color clarity depth table price x y z
30 31 0.23 Very Good F VS1 60.0 57.0 402 4.00 4.03 2.41
31 32 0.23 Very Good F VS1 59.8 57.0 402 4.04 4.06 2.42
32 33 0.23 Very Good E VS1 60.7 59.0 402 3.97 4.01 2.42
33 34 0.23 Very Good E VS1 59.5 58.0 402 4.01 4.06 2.40
34 35 0.23 Very Good D VS1 61.9 58.0 402 3.92 3.96 2.44
... ... ... ... ... ... ... ... ... ... ... ...
53938 53939 0.86 Premium H SI2 61.0 58.0 2757 6.15 6.12 3.74
53939 53940 0.75 Ideal D SI2 62.2 55.0 2757 5.83 5.87 3.64
53940 53941 0.71 Premium E SI1 60.5 55.0 2756 5.79 5.74 3.49
53941 53942 0.71 Premium F SI1 59.8 62.0 2756 5.74 5.73 3.43
53942 53943 0.70 Very Good E VS2 60.5 59.0 2757 5.71 5.76 3.47

53692 rows × 11 columns

Группировка и агрегация данных

  1. Средняя стоимость по типу огранки
In [9]:
df.groupby(["cut"])[["price"]].mean()
Out[9]:
price
cut
Fair 4358.757764
Good 3928.864452
Ideal 3457.541970
Premium 4583.992605
Very Good 3981.658529
  1. Средний вес по типу огранки
In [10]:
df.groupby("cut")[["carat"]].mean()
Out[10]:
carat
cut
Fair 1.046137
Good 0.849185
Ideal 0.702837
Premium 0.891929
Very Good 0.806373

Сортировка данных

  1. Сортировка по цене по убыванию
In [11]:
df.sort_values("price", ascending=False)
Out[11]:
id carat cut color clarity depth table price x y z
27749 27750 2.29 Premium I VS2 60.8 60.0 18823 8.50 8.47 5.16
27748 27749 2.00 Very Good G SI1 63.5 56.0 18818 7.90 7.97 5.04
27747 27748 1.51 Ideal G IF 61.7 55.0 18806 7.37 7.41 4.56
27746 27747 2.07 Ideal G SI2 62.5 55.0 18804 8.20 8.13 5.11
27745 27746 2.00 Very Good H SI1 62.8 57.0 18803 7.95 8.00 5.01
... ... ... ... ... ... ... ... ... ... ... ...
4 5 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75
3 4 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63
2 3 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31
1 2 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31
0 1 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43

53943 rows × 11 columns

  1. Сортировка по нескольким столбцам
In [12]:
df.sort_values(["carat", "price"], ascending=[True, False])
Out[12]:
id carat cut color clarity depth table price x y z
31591 31592 0.20 Premium E VS2 59.8 62.0 367 3.79 3.77 2.26
31592 31593 0.20 Premium E VS2 59.0 60.0 367 3.81 3.78 2.24
31593 31594 0.20 Premium E VS2 61.1 59.0 367 3.81 3.78 2.32
31594 31595 0.20 Premium E VS2 59.7 62.0 367 3.84 3.80 2.28
31595 31596 0.20 Ideal E VS2 59.7 55.0 367 3.86 3.84 2.30
... ... ... ... ... ... ... ... ... ... ... ...
25998 25999 4.01 Premium I I1 61.0 61.0 15223 10.14 10.10 6.17
25999 26000 4.01 Premium J I1 62.5 62.0 15223 10.02 9.94 6.24
27130 27131 4.13 Fair H I1 64.8 61.0 17329 10.00 9.85 6.43
27630 27631 4.50 Fair J I1 65.8 58.0 18531 10.23 10.16 6.72
27415 27416 5.01 Fair J I1 65.5 59.0 18018 10.74 10.54 6.98

53943 rows × 11 columns

Удаление строк/столбцов

  1. Удаление столбца
In [13]:
df.drop("depth", axis=1)
Out[13]:
id carat cut color clarity table price x y z
0 1 0.23 Ideal E SI2 55.0 326 3.95 3.98 2.43
1 2 0.21 Premium E SI1 61.0 326 3.89 3.84 2.31
2 3 0.23 Good E VS1 65.0 327 4.05 4.07 2.31
3 4 0.29 Premium I VS2 58.0 334 4.20 4.23 2.63
4 5 0.31 Good J SI2 58.0 335 4.34 4.35 2.75
... ... ... ... ... ... ... ... ... ... ...
53938 53939 0.86 Premium H SI2 58.0 2757 6.15 6.12 3.74
53939 53940 0.75 Ideal D SI2 55.0 2757 5.83 5.87 3.64
53940 53941 0.71 Premium E SI1 55.0 2756 5.79 5.74 3.49
53941 53942 0.71 Premium F SI1 62.0 2756 5.74 5.73 3.43
53942 53943 0.70 Very Good E VS2 59.0 2757 5.71 5.76 3.47

53943 rows × 10 columns

Удаление строки

In [14]:
df.drop(0, axis=0)
Out[14]:
id carat cut color clarity depth table price x y z
1 2 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31
2 3 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31
3 4 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63
4 5 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75
5 6 0.24 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48
... ... ... ... ... ... ... ... ... ... ... ...
53938 53939 0.86 Premium H SI2 61.0 58.0 2757 6.15 6.12 3.74
53939 53940 0.75 Ideal D SI2 62.2 55.0 2757 5.83 5.87 3.64
53940 53941 0.71 Premium E SI1 60.5 55.0 2756 5.79 5.74 3.49
53941 53942 0.71 Premium F SI1 59.8 62.0 2756 5.74 5.73 3.43
53942 53943 0.70 Very Good E VS2 60.5 59.0 2757 5.71 5.76 3.47

53942 rows × 11 columns

Создание новых столбцов

  1. Создание нового столбца "стоимость 1 карата"
In [15]:
df["price_carat"] = df["price"] / df["carat"]
df[["price_carat"]]
Out[15]:
price_carat
0 1417.391304
1 1552.380952
2 1421.739130
3 1151.724138
4 1080.645161
... ...
53938 3205.813953
53939 3676.000000
53940 3881.690141
53941 3881.690141
53942 3938.571429

53943 rows × 1 columns

Удаление строк с пустыми значениями

  1. Удаление строк с NaN
In [16]:
df.dropna()
Out[16]:
id carat cut color clarity depth table price x y z price_carat
0 1 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43 1417.391304
1 2 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31 1552.380952
2 3 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31 1421.739130
3 4 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63 1151.724138
4 5 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75 1080.645161
... ... ... ... ... ... ... ... ... ... ... ... ...
53938 53939 0.86 Premium H SI2 61.0 58.0 2757 6.15 6.12 3.74 3205.813953
53939 53940 0.75 Ideal D SI2 62.2 55.0 2757 5.83 5.87 3.64 3676.000000
53940 53941 0.71 Premium E SI1 60.5 55.0 2756 5.79 5.74 3.49 3881.690141
53941 53942 0.71 Premium F SI1 59.8 62.0 2756 5.74 5.73 3.43 3881.690141
53942 53943 0.70 Very Good E VS2 60.5 59.0 2757 5.71 5.76 3.47 3938.571429

53943 rows × 12 columns

  1. Заполнить пустые значения для определённого столбца
In [17]:
df.fillna({"price": df["price"].mean()}, inplace=True)

Заполнение пустых значений

  1. Заполнение средним значением
In [19]:
cut_mapping = {'Fair': 0, 'Good': 1, 'Very Good': 2, 'Premium': 3, 'Ideal': 4}
df['cut'] = df['cut'].map(cut_mapping)

color_mapping = {'J': 0, 'I': 1, 'H': 2, 'G': 3, 'F': 4, 'E': 5, 'D': 6} 
df['color'] = df['color'].map(color_mapping)

clarity_mapping = {'I1': 0, 'SI2': 1, 'SI1': 2, 'VS2': 3, 'VS1': 4, 'VVS2': 5, 'VVS1': 6, 'IF': 7} 
df['clarity'] = df['clarity'].map(clarity_mapping)

df.fillna(df.mean(), inplace=True)

Визуализация данных с Pandas и Matplotlib

  1. Линейная диаграмма (plot). Вес бриллиантов
In [27]:
import matplotlib.pyplot as plt
df.plot(x="id", y="carat", kind="line")

plt.xlabel("id") 
plt.ylabel("weight")
plt.title("Weight of diamonds")

plt.show()
No description has been provided for this image
  1. Столбчатая диаграмма (bar). Соотношение цены и веса
In [28]:
df.plot(x="carat", y="price", kind="bar")

plt.xlabel("weight") 
plt.ylabel("price")
plt.title("Price-Weight")

plt.show()
No description has been provided for this image
  1. Гистограмма (hist). Частота встречаемости по глубине
In [6]:
df["depth"].plot(kind="hist")

plt.xlabel("depth") 
plt.ylabel("Frequency") 
plt.title("Frequency of depth") 

plt.show()
No description has been provided for this image
  1. Ящик с усами (box). Вес
In [11]:
df["carat"].plot(kind="box")

plt.ylabel("weight (carat)") 
plt.title("Box Plot of diamond weight") 

plt.show()
No description has been provided for this image
  1. Диаграмма с областями (area).
In [12]:
df.plot(x="id", y="price", kind="area")

plt.xlabel("id") 
plt.ylabel("price")
plt.title("Price by id diamonds")

plt.show()
No description has been provided for this image
  1. Диаграмма рассеяния (scatter). Зависимость цены от веса
In [25]:
df.plot(kind="scatter", x="carat", y="price")

plt.xlabel("weight") 
plt.ylabel("price")
plt.title("The dependence of price on weight") 

plt.show()
No description has been provided for this image
  1. Круговая диаграмма (pie). Прозрачность
In [19]:
# Определение порога для объединения редких значений
threshold = 0.02  # Порог 2%

# Подсчёт количества уникальных значений и расчёт частот
value_counts = df["clarity"].value_counts()
total_count = value_counts.sum()

# Условие для агрегации значений ниже порога
other_values = value_counts[value_counts / total_count < threshold].sum()
main_values = value_counts[value_counts / total_count >= threshold]

# Добавление категории "Other"
main_values["Other"] = other_values

# Построение диаграммы
main_values.plot(kind="pie", 
                 autopct='%1.1f%%',  # Проценты
                 startangle=90,      # Начальный угол
                 counterclock=False, # По часовой стрелке
                 cmap="Set3",        # Цветовая схема
                 wedgeprops={'edgecolor': 'black'}) # Границы сегментов

plt.title("Distribution of Daily Customer Count in Stores (Aggregated)")
plt.subplots_adjust(left=0.3, right=0.7, top=0.9, bottom=0.1)
plt.show()
No description has been provided for this image