Passed
Push — master ( d5b48a...5a31d8 )
by Simon
01:07
created

convert_dataframe()   A

Complexity

Conditions 3

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 28
rs 9.45
c 0
b 0
f 0
cc 3
nop 3
1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
import numpy as np
6
import pandas as pd
7
8
9
def convert_dataframe(dataframe1, search_space1, search_space2):
10
    dataframe2 = dataframe1.copy()
11
12
    for para1 in search_space1:
13
        if para1 not in search_space2:
14
            dataframe2.drop(para1, axis=1, inplace=True)
15
            continue
16
17
        search_elements1 = search_space1[para1]
18
        search_elements2 = search_space2[para1]
19
20
        both = set(search_elements1).intersection(search_elements2)
21
22
        indices_A = [search_elements1.index(x) for x in both]
23
        indices_B = [search_elements2.index(x) for x in both]
24
25
        conv_dict = dict(zip(indices_A, indices_B))
26
27
        col = dataframe2[para1]
28
        col_conv = col.map(conv_dict)
29
        col_conv = col_conv.dropna(how="any")
30
        col_conv = col_conv.astype(int)
31
32
        dataframe2[para1] = col_conv
33
34
    dataframe2 = dataframe2.dropna(how="any", axis=0)
35
36
    return dataframe2
37
38
39
def memory_dict2dataframe(memory_dict, search_space):
40
    columns = list(search_space.keys())
41
42
    if not bool(memory_dict):
43
        print("Memory dictionary is empty.")
44
        return pd.DataFrame([], columns=columns)
45
46
    pos_tuple_list = list(memory_dict.keys())
47
    result_list = list(memory_dict.values())
48
49
    results_df = pd.DataFrame(result_list)
50
    np_pos = np.array(pos_tuple_list)
51
52
    pd_pos = pd.DataFrame(np_pos, columns=columns)
53
    dataframe = pd.concat([pd_pos, results_df], axis=1)
54
55
    return dataframe
56
57
58
def dataframe2memory_dict(dataframe, search_space):
59
    columns = list(search_space.keys())
60
61
    if dataframe.empty:
62
        print("Memory dataframe is empty.")
63
        return {}
64
65
    positions = dataframe[columns]
66
    scores = dataframe.drop(columns, axis=1)
67
68
    scores = scores.to_dict("records")
69
    positions_list = positions.values.tolist()
70
71
    # list of lists into list of tuples
72
    pos_tuple_list = list(map(tuple, positions_list))
73
    memory_dict = dict(zip(pos_tuple_list, scores))
74
75
    return memory_dict
76
77