-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_features.py
More file actions
167 lines (138 loc) · 4.07 KB
/
Copy pathbuild_features.py
File metadata and controls
167 lines (138 loc) · 4.07 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""Process data for network intrusion detection."""
import copy
import pandas as pd
def drop_features(
df: pd.DataFrame,
drop: list[str],
verbose: bool = True
) -> pd.DataFrame:
"""
Drop features by name from DataFrame
Parameters
----------
df : pd.DataFrame
Input DataFrame
drop : list, default None
List of column names to drop
verbose : bool, default True
Print information
Returns
-------
pd.DataFrame
DataFrame with named features removed
"""
if verbose:
print('='*70)
print('Drop Features by Name')
print('-'*70)
n_cols_before = len(df.columns)
not_found = [col for col in drop if col not in df.columns]
if not_found:
raise ValueError(f'{not_found} not found in df')
df = df.drop(columns=drop)
if verbose:
n_cols_dropped = len(drop)
print(f'Dropped {n_cols_dropped} columns:')
for col in drop:
print(f'- {col}')
print()
n_cols_after = len(df.columns)
print('-'*70)
print(f'Columns Before: {n_cols_before}')
print(f'Columns After: {n_cols_after}')
print()
return df
def indicate_service(
df: pd.DataFrame,
service_port_map: dict[str, list[int]],
port_column: str = 'destination_port',
verbose: bool = True
) -> pd.DataFrame:
"""
Indicate service name prior to dropping port-number column.
Parameters
----------
df : pd.DataFrame
Input DataFrame
service_port_map : dict[str, list[int]]
Mapping of service names to lists of port numbers
Example: {'ssh': [22], 'ftp': [20,21]}
port_column : str, default 'destination_port'
Name of column with port numbers to drop
verbose : bool, default True
Print information
Returns
-------
pd.DataFrame
DataFrame with indicator variables for services instead of
column with port numbers.
"""
if verbose:
print('='*70)
print('Indicate Services')
print('-'*70)
df = df.copy()
for service, ports in service_port_map.items():
service_column = f'is_{service}'
df[service_column] = df[port_column].isin(ports).astype(int)
if verbose:
print(f'Ports {ports} -> {service_column}')
df = df.drop(columns=port_column)
if verbose:
print()
print(f'{port_column} was dropped.')
print()
return df
def keep_features(
data: dict,
keep: list,
X_keys: list = ['X_train', 'X_test'],
list_features: bool = True,
verbose: bool = True
) -> dict:
"""
Keep features in data splits (dropping all others).
Parameters
----------
data : dict
Input data splits
keep : list
List of column names to keep
X_keys : list, default ['X_train','X_test']
List of keys in data to process
list_features : bool, default True
If True, and verbose is True, lists features kept after
dropping other features
verbose : bool, default True
Print information
Returns
-------
dict
Data splits with features kept
"""
if verbose:
print('-'*70)
print('Keep Features')
print('-'*70)
_data = copy.deepcopy(data)
for key in X_keys:
if key not in _data:
if verbose:
print(f"Warning: '{key}' not found in data. Skipping.")
print()
continue
missing = [col for col in keep if col not in _data[key].columns]
if missing:
raise ValueError(
f"Features not found in data['{key}']: {missing}"
)
drop = [col for col in _data[key].columns if col not in keep]
_data[key] = _data[key].drop(columns=drop)
if verbose:
cols = _data[key].columns
print(f"Kept {len(cols)} columns in data['{key}'].")
if list_features:
for col in cols:
print(f'- {col}')
print()
return _data