213 KiB
213 KiB
Работа с NumPy
In [1]:
import numpy as np
matrix = np.array([[4, 5, 0], [9, 9, 9]])
print("matrix = \n", matrix, "\n")
tmatrix = matrix.T
print("tmatrix = \n", tmatrix, "\n")
vector = np.ravel(matrix)
print("vector = \n", vector, "\n")
tvector = np.reshape(vector, (6, 1))
print("tvector = \n", tvector, "\n")
list_matrix = list(matrix)
print("list_matrix = \n", list_matrix, "\n")
str_matrix = str(matrix)
print("matrix as str = \n", str_matrix, "\n")
print("matrix type is", type(matrix), "\n")
print("vector type is", type(vector), "\n")
print("list_matrix type is", type(list_matrix), "\n")
print("str_matrix type is", type(str_matrix), "\n")
formatted_vector = "; ".join(map(str, vector))
print("formatted_vector = \n", formatted_vector, "\n")
Работа с Pandas DataFrame
Работа с данными - чтение и запись CSV
In [3]:
import pandas as pd
df = pd.read_csv("../data/car_price_prediction.csv")
df.to_csv("../data/test.csv")
Работа с данными - основные команды
In [70]:
df.info()
print(df.describe().transpose())
cleared_df = df.drop(["Color", "Leather interior"], axis=1)
print(cleared_df.head())
print(cleared_df.tail())
sorted_df = cleared_df.sort_values(by="Price")
print(sorted_df.head())
print(sorted_df.tail())
Работа с данными - работа с элементами
In [20]:
print(df["Model"])
print(df.loc[100])
print(df.loc[100, "Price"])
print(df.loc[100:200, ["Model", "Price"]])
print(df[0:3])
print(df.iloc[0])
print(df.iloc[3:5, 0:2])
print(df.iloc[[3, 4], [0, 1]])
Работа с данными - отбор и группировка
In [24]:
s_values = df["Manufacturer"].unique()
print(s_values)
s_total = 0
for s_value in s_values:
count = df[df["Manufacturer"] == s_value].shape[0]
s_total += count
print(s_value, "count =", count)
print("Total count = ", s_total)
print(df.groupby(["Model", "Category"]).size().reset_index(name="Count")) # type: ignore
Визуализация - Исходные данные
In [26]:
data = df[["Manufacturer", "Model", "Levy"]].copy()
data.dropna(subset=["Levy"], inplace=True)
print(data)
In [45]:
def q1(x):
return x.quantile(0.25)
# median = quantile(0.5)
def q2(x):
return x.quantile(0.5)
def q3(x):
return x.quantile(0.75)
def iqr(x):
return q3(x) - q1(x)
def low_iqr(x):
return max(0, q1(x) - 1.5 * iqr(x))
def high_iqr(x):
return q3(x) + 1.5 * iqr(x)
quantiles = df[["Manufacturer", "Prod. year"]].groupby(["Manufacturer"]).aggregate(["min", q1, q2, "median", q3, "max"])
print(quantiles)
iqrs = (
df[["Manufacturer", "Prod. year"]].groupby(["Manufacturer"]).aggregate([low_iqr, iqr, high_iqr])
)
print(iqrs)
df.boxplot(column="Prod. year", by="Manufacturer")
Out[45]:
Визуализация - Гистограмма
In [52]:
df.plot.hist(column=["Prod. year"], bins=80)
Out[52]:
Визуализация - Точечная диаграмма
In [58]:
df.plot.scatter(x="Fuel type", y="Category")
Out[58]:
Визуализация - Столбчатая диаграмма
In [62]:
plot = df.groupby(["Category", "Gear box type"]).size().unstack().plot.bar(color=["pink", "green"])
plot.legend(["Automatic","Not automatic"])
Out[62]:
Визуализация - Временные ряды
In [78]:
from datetime import datetime
import matplotlib.dates as md
dt = pd.read_csv("../data/car_price_prediction.csv")
ts = dt[["Manufacturer","Price","Prod. year"]].copy()
tf = ts["Manufacturer"].unique()
ts["date"] = ts["Prod. year"].astype(str)
ts["date"] = ts.apply(lambda row: datetime.strptime(row["date"], "%Y"), axis=1)
ts.info()
print(ts)
plot = ts.plot.line(x="date", y="Price")
plot.xaxis.set_major_locator(md.DayLocator(interval=1))
plot.xaxis.set_major_formatter(md.DateFormatter("%Y"))
plot.tick_params(axis="x", labelrotation=90)