Files
DataScience/lab_1.ipynb

194 KiB
Raw Permalink Blame History

Импорты всех зависимостей

In [180]:
import pandas as pd

from src.path_utils import *
from src.notebook_utils import *

Создание датафрейма путем чтения данных из .csv файла

In [201]:
df = pd.read_csv(DATA_SCIENCE_SALARIES_CSV_PATH)
df_reserve = df.copy()

Работа с библиотекой pandas

In [202]:
print_header('Загрузка данных из датафрейма в .csv файл')
df.to_csv(TEST_DOWNLOAD_CSV_PATH, index=False)

print_header('Информация о файле')
df.info()

print_header('Вывод данных одной колонке')
print(df['salary_in_usd'])

print_header('Конкретная запись')
print(df.loc[10])

print_header('Конкретная колонка из конкретной записи')
print(df.loc[10, 'salary_in_usd'])

print_header('Срез всех данных')
print(df.loc[10:13])

print_header('Срез данных конкретной колонки')
print(df.loc[10:13, 'salary_in_usd'])

print_header('Срез данных по диапазону строк и колонок')
print(df.iloc[10:13, 0:5])

print_header('Получение уникальных данных по колонке')
print(df['employee_residence'].unique())

print_header('Группировка данных')
print(df.groupby(['job_title', 'experience_level']).size().reset_index(name='count'))

print_header('Сортировка данных')
print(df_reserve.sort_values('job_title'))

print_header('Удаление первых записей')
df_reserve.drop(df.head(500).index, inplace=True)
print('Разница: {diff}'.format(diff = df.shape[0] - df_reserve.shape[0]))

print_header('Отсечение последних записей')
df_reserve = df_reserve.tail(-100)
print('Разница: {diff}'.format(diff = df.shape[0] - df_reserve.shape[0]))

print_header('Создание новых столбцов')
df_reserve = df_reserve.assign(salary_in_rub = df['salary_in_usd'] * 100)
df_reserve.info()
print(df_reserve['salary_in_rub'])

print_header('Удаление строк с пустыми значениями в конкретной колонке')
df_reserve.dropna(subset = 'job_title', inplace = True)

print_header('Заполнение пустых значений')
source_column = 'salary'
replace_column = 'salary_in_usd'
empty_indexes = df_reserve[source_column][df_reserve[source_column].isnull()].index
for idx in empty_indexes:
    source_value = df_reserve[replace_column][idx]
    if pd.notna(source_value):
        df_reserve.at[idx, source_column] = source_value
print(df_reserve[source_column])
---| Загрузка данных из датафрейма в .csv файл |---


---| Информация о файле |---

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3755 entries, 0 to 3754
Data columns (total 11 columns):
 #   Column              Non-Null Count  Dtype 
---  ------              --------------  ----- 
 0   work_year           3755 non-null   int64 
 1   experience_level    3755 non-null   object
 2   employment_type     3755 non-null   object
 3   job_title           3755 non-null   object
 4   salary              3755 non-null   int64 
 5   salary_currency     3755 non-null   object
 6   salary_in_usd       3755 non-null   int64 
 7   employee_residence  3755 non-null   object
 8   remote_ratio        3755 non-null   int64 
 9   company_location    3755 non-null   object
 10  company_size        3755 non-null   object
dtypes: int64(4), object(7)
memory usage: 322.8+ KB

---| Вывод данных одной колонке |---

0        85847
1        30000
2        25500
3       175000
4       120000
         ...  
3750    412000
3751    151000
3752    105000
3753    100000
3754     94665
Name: salary_in_usd, Length: 3755, dtype: int64

---| Конкретная запись |---

work_year                       2023
experience_level                  SE
employment_type                   FT
job_title             Data Scientist
salary                         90700
salary_currency                  USD
salary_in_usd                  90700
employee_residence                US
remote_ratio                       0
company_location                  US
company_size                       M
Name: 10, dtype: object

---| Конкретная колонка из конкретной записи |---

90700

---| Срез всех данных |---

    work_year experience_level employment_type          job_title  salary  \
10       2023               SE              FT     Data Scientist   90700   
11       2023               SE              FT       Data Analyst  130000   
12       2023               SE              FT       Data Analyst  100000   
13       2023               EN              FT  Applied Scientist  213660   

   salary_currency  salary_in_usd employee_residence  remote_ratio  \
10             USD          90700                 US             0   
11             USD         130000                 US           100   
12             USD         100000                 US           100   
13             USD         213660                 US             0   

   company_location company_size  
10               US            M  
11               US            M  
12               US            M  
13               US            L  

---| Срез данных конкретной колонки |---

10     90700
11    130000
12    100000
13    213660
Name: salary_in_usd, dtype: int64

---| Срез данных по диапазону строк и колонок |---

    work_year experience_level employment_type       job_title  salary
10       2023               SE              FT  Data Scientist   90700
11       2023               SE              FT    Data Analyst  130000
12       2023               SE              FT    Data Analyst  100000

---| Получение уникальных данных по колонке |---

['ES' 'US' 'CA' 'DE' 'GB' 'NG' 'IN' 'HK' 'PT' 'NL' 'CH' 'CF' 'FR' 'AU'
 'FI' 'UA' 'IE' 'IL' 'GH' 'AT' 'CO' 'SG' 'SE' 'SI' 'MX' 'UZ' 'BR' 'TH'
 'HR' 'PL' 'KW' 'VN' 'CY' 'AR' 'AM' 'BA' 'KE' 'GR' 'MK' 'LV' 'RO' 'PK'
 'IT' 'MA' 'LT' 'BE' 'AS' 'IR' 'HU' 'SK' 'CN' 'CZ' 'CR' 'TR' 'CL' 'PR'
 'DK' 'BO' 'PH' 'DO' 'EG' 'ID' 'AE' 'MY' 'JP' 'EE' 'HN' 'TN' 'RU' 'DZ'
 'IQ' 'BG' 'JE' 'RS' 'NZ' 'MD' 'LU' 'MT']

---| Группировка данных |---

                         job_title experience_level  count
0    3D Computer Vision Researcher               EN      2
1    3D Computer Vision Researcher               MI      1
2    3D Computer Vision Researcher               SE      1
3                     AI Developer               EN      6
4                     AI Developer               MI      2
..                             ...              ...    ...
187             Research Scientist               SE     49
188         Software Data Engineer               MI      1
189         Software Data Engineer               SE      1
190             Staff Data Analyst               EX      1
191           Staff Data Scientist               SE      1

[192 rows x 3 columns]

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

      work_year experience_level employment_type  \
2149       2021               EN              FT   
2206       2022               EN              FT   
2022       2022               SE              FT   
3537       2021               MI              PT   
985        2023               EN              FT   
...         ...              ...             ...   
1331       2023               SE              FT   
732        2023               MI              FT   
856        2023               SE              FL   
183        2020               EX              FT   
3631       2021               SE              CT   

                          job_title  salary salary_currency  salary_in_usd  \
2149  3D Computer Vision Researcher   20000             USD          20000   
2206  3D Computer Vision Researcher   50000             USD          50000   
2022  3D Computer Vision Researcher   10000             USD          10000   
3537  3D Computer Vision Researcher  400000             INR           5409   
985                    AI Developer   60000             EUR          64385   
...                             ...     ...             ...            ...   
1331             Research Scientist  248100             USD         248100   
732          Software Data Engineer  100000             SGD          75020   
856          Software Data Engineer   50000             USD          50000   
183              Staff Data Analyst   15000             USD          15000   
3631           Staff Data Scientist  105000             USD         105000   

     employee_residence  remote_ratio company_location company_size  
2149                 AS             0               AS            M  
2206                 US           100               CR            S  
2022                 CA            50               AL            S  
3537                 IN            50               IN            M  
985                  DE             0               DE            M  
...                 ...           ...              ...          ...  
1331                 CA             0               CA            M  
732                  SG           100               SG            L  
856                  NG            50               AU            M  
183                  NG             0               CA            M  
3631                 US           100               US            M  

[3755 rows x 11 columns]

---| Удаление первых записей |---

Разница: 500

---| Отсечение последних записей |---

Разница: 600

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

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3155 entries, 600 to 3754
Data columns (total 12 columns):
 #   Column              Non-Null Count  Dtype 
---  ------              --------------  ----- 
 0   work_year           3155 non-null   int64 
 1   experience_level    3155 non-null   object
 2   employment_type     3155 non-null   object
 3   job_title           3155 non-null   object
 4   salary              3155 non-null   int64 
 5   salary_currency     3155 non-null   object
 6   salary_in_usd       3155 non-null   int64 
 7   employee_residence  3155 non-null   object
 8   remote_ratio        3155 non-null   int64 
 9   company_location    3155 non-null   object
 10  company_size        3155 non-null   object
 11  salary_in_rub       3155 non-null   int64 
dtypes: int64(5), object(7)
memory usage: 295.9+ KB
600     12900000
601      9270000
602      6180000
603     17230900
604      6009300
          ...   
3750    41200000
3751    15100000
3752    10500000
3753    10000000
3754     9466500
Name: salary_in_rub, Length: 3155, dtype: int64

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


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

600      129000
601       92700
602       61800
603      164000
604       56000
         ...   
3750     412000
3751     151000
3752     105000
3753     100000
3754    7000000
Name: salary, Length: 3155, dtype: int64

Линейная диаграмма

In [200]:
df.groupby('experience_level')['salary_in_usd'].mean().plot.line(x = 'salary_in_usd', y = 'work_year')
Out[200]:
<Axes: xlabel='experience_level'>
No description has been provided for this image

Столбчатая диаграмма

In [199]:
df.groupby('experience_level')['salary_in_usd'].mean().plot.bar(x = 'experience_level', y = 'salary_in_usd')
Out[199]:
<Axes: xlabel='experience_level'>
No description has been provided for this image

Гистограмма

In [198]:
df['salary_in_usd'].value_counts().plot.hist()
Out[198]:
<Axes: ylabel='Frequency'>
No description has been provided for this image

Ящик с усами

In [197]:
df['salary_in_usd'].plot.box()
Out[197]:
<Axes: >
No description has been provided for this image

Диаграмма с областями

In [196]:
pd.DataFrame({
    'salary': df.loc[1:100, 'salary'],
    'salary_in_usd': df.loc[1:100, 'salary_in_usd'],
    'experience_level': df.loc[1:100, 'experience_level'],
}).plot.area(x='experience_level')
Out[196]:
<Axes: xlabel='experience_level'>
No description has been provided for this image

Диаграмма рассеяния

In [195]:
df.plot.scatter(x = 'experience_level', y = 'salary_currency')
Out[195]:
<Axes: xlabel='experience_level', ylabel='salary_currency'>
No description has been provided for this image

Круговая диаграмма

In [194]:
df['experience_level'].value_counts().plot.pie()
Out[194]:
<Axes: ylabel='count'>
No description has been provided for this image