183 KiB
183 KiB
Работа с NumPy
In [270]:
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 [271]:
import pandas as pd
df = pd.read_csv("../data/ds_salaries.csv")
df.to_csv("../data/test.csv")
Работа с данными - основные команды
In [272]:
df.info()
print(df.describe().transpose())
In [273]:
cleared_df = df.drop(["work_year", "experience_level"], axis=1)
print(cleared_df.head(1))
print(cleared_df.tail(2))
In [274]:
sorted_df = cleared_df.sort_values(by="salary")
print(sorted_df.head(3))
print(sorted_df.tail(1))
Работа с данными - работа с элементами
In [275]:
print(df["salary"])
In [276]:
print(df[0:3])
In [277]:
print(df.loc[0])
In [278]:
print(df.loc[100, "employment_type"])
In [279]:
print(df.loc[100:200, ["salary", "employment_type"]])
In [280]:
print(df.iloc[0])
In [281]:
print(df.iloc[3:5, 0:2])
In [282]:
print(df.iloc[[3, 4], [0, 1]])
Работа с данными - отбор и группировка
In [283]:
s_values = df["work_year"].unique()
print(s_values)
In [284]:
s_total = 0
for s_value in s_values:
count = df[df["work_year"] == s_value].shape[0]
s_total += count
print(s_value, "count =", count)
print("Total count = ", s_total)
In [285]:
print(df.groupby(["job_title", "experience_level"]).size().reset_index(name="total_count").sort_values(by="total_count")) # type: ignore
Визуализация - Исходные данные
In [286]:
data = df[["work_year", "salary", "employee_residence"]].copy()
data.dropna(subset=["employee_residence"], inplace=True)
print(data)
Визуализация - Сводка пяти чисел
In [287]:
def q1(x):
return x.quantile(0.250)
# median = quantile(0.5)
def q2(x):
return x.quantile(0.5)
def q3(x):
return x.quantile(0.750)
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)
data = data.where(data["salary"] < 3000000)
quantiles = (
data[["work_year", "salary"]]
.groupby(["work_year"])
.aggregate(["min", q1, q2, "median", q3, "max"])
)
print(quantiles)
iqrs = (
data[["work_year", "salary"]]
.groupby(["work_year"])
.aggregate([low_iqr, iqr, high_iqr])
)
print(iqrs)
data.boxplot(column="salary", by="work_year")
Out[287]:
Визуализация - Гистограмма
In [288]:
df.plot.hist(column=["work_year"], bins=80)
Out[288]:
Визуализация - Точечная диаграмма
In [289]:
df.plot.scatter(x="work_year", y="salary")
df.plot.scatter(x="experience_level", y="salary")
Out[289]:
Визуализация - Столбчатая диаграмма
In [290]:
plot = (
df.groupby(["work_year", "remote_ratio"])
.size()
.unstack()
.plot.bar(color=["pink", "green", "red"])
)
Визуализация - Временные ряды
In [291]:
from datetime import datetime
import matplotlib.dates as md
ts = pd.read_csv("../data/dollar.csv")
ts["date"] = ts.apply(lambda row: datetime.strptime(row["my_date"], "%d.%m.%Y"), axis=1)
plot = ts.plot.line(x="date", y="my_value")
plot.xaxis.set_major_locator(md.DayLocator(interval=10))
plot.xaxis.set_major_formatter(md.DateFormatter("%d.%m.%Y"))
plot.tick_params(axis="x", labelrotation=90)