-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
139 lines (113 loc) · 4.15 KB
/
utils.py
File metadata and controls
139 lines (113 loc) · 4.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
"""
Утилитки_для_помощи_в_обработке_данных
"""
import os
import sys
import json
import pandas as pd
import matplotlib as mplt
import seaborn as sns
import luigi
mplt.use('Agg')
strip_meta_path = lambda path: path.split('/')[-1:][0].strip('.json')
def get_meta_data(target):
"""
Получаем данные из meta file
target: luigi target instace\или путь к мета файлу
"""
if isinstance(target, str):
with open(target, 'r') as meta_file:
meta_data = meta_file.readline()
else:
with target.open('r') as meta_file:
meta_data = meta_file.readline()
return json.loads(meta_data)
def rewrite_file(target, content):
"""
Функция перезаписи файла
target: путь к мета файлу
content: содержимое файла
"""
os.remove(target)
with open(target, 'w') as meta_file:
meta_file.write(json.dumps(content))
#===============================================================================
def get_data(fpath):
"""
получаем данные из файла
"""
return pd.read_csv(fpath)
def get_unique(dataframe):
"""
Оцениваем количество уникальных данных
"""
print('=' * 50)
print('Data count by columns:\n')
for i in dataframe.columns:
print(i, ' ----> ', dataframe[i].nunique())
print('-' * 50)
print('Shape: ', dataframe.shape)
def get_nan_by_columns_count(dataframe):
"""
Оцениваем относительное число пропусков по каждому столбцу
"""
print('=' * 50)
print('Nan counts:\n')
for i in dataframe.columns:
print(
i,
' ----> ',
(dataframe[dataframe[i].isnull() == True][i].size * 1.0)\
/dataframe.index.size
)
def get_correlation_column_by_target(dataframe, target):
"""
Сыитаем корреляцию между столбцами и целевым столбцом признаков
"""
if target not in dataframe.columns:
raise ValueError
print('=' * 50)
print('Correlateion {0} with columns:\n'.format(target))
for i in dataframe.columns:
print(
i,
' ----> ',
dataframe[target].corr(dataframe[i])
)
#def do_plot(dataframe, target):
# """
# СТроит распределение случайных величин в столбцах в зависимости от наличия
# признака в строке, сохраняет картинки в текущую папку
# """
# for i in dataframe.columns:
# tmp_fig = sns.
def main(path_to_data):
"""
Основная функция оценки данных
"""
dataframe = get_data(path_to_data)
get_unique(dataframe)
get_nan_by_columns_count(dataframe)
get_correlation_column_by_target(dataframe, 'Delinquent90')
#===============================================================================
#TODO надо орагнизовать слеюдущий алгоритмы:
# - для быстрого результата - заполнить данные и посчитать каким нибудь простым
# алгоритмом
# - но основной подход должен быть следующий:
# --- оценка нормальности распрделения фич;
# --- заолпнение пропусков в данных, дроп результатов;
# --- построение модели, подгонка параметров
#===============================================================================
if __name__ == "__main__":
print(sys.argv)
if len(sys.argv) != 2:
print('Input path to target csv_data')
else:
if os.path.exists(sys.argv[1]):
#оценим данные
main(sys.argv[1])
else:
print('Path is not exists')