-
Notifications
You must be signed in to change notification settings - Fork 2
/
data.py
178 lines (131 loc) · 5.11 KB
/
data.py
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
168
169
170
171
172
173
174
175
176
177
178
"""This file aims to create the input for the model
"""
import numpy as np
import pandas as pd
import datetime as dt
def expand_cases_to_vector(data):
"""Receives the cases dataframe and expands it, creating a row per each day
time lapse.
"""
dates_num = len(data.columns) - 1
dates = data.columns[1:].tolist()
countries = data["Country"].unique().tolist()
#print(f"Total countries: {len(countries)}")
#print(f"Total Dates: {dates_num}")
# Empty template to fill with data
rows = (dates_num-1) * len(countries)
output = pd.DataFrame( \
columns=[
"Country",
"Date",
"Cases",
"Popden",
"Masks",
"Poprisk",
"Lockdown",
"Borders",
"NextDay"
])
for j in range(len(countries)):
# Cases data from the country row
country_data = data[ data["Country"] == countries[j] ].values.tolist()
country_data = country_data[0][1:]
for i in range(dates_num-1):
output.loc[len(output)] = [countries[j],
dates[i],
country_data[i],
0, 0, 0, 0, 0,
country_data[i+1]]
return output
def split_by_date(df, limit_date):
"""Splits the dataframe in two new dataframes based on the
specified limit date in format mm/dd/yy
"""
mask = [dt.datetime.strptime(date, r"%m/%d/%y") <= \
dt.datetime.strptime(limit_date, r"%m/%d/%y") \
for date in df["Date"].values.tolist()]
inverse = [not item for item in mask]
before = df.loc[mask]
after = df.loc[inverse]
return before, after
def fill_df_column_with_value(df, colname, source_df, source_col, default):
"""Takes the specified column from the source dataframe and inserts its data
wisely in the specified column of the target dataframe. It admits a default
value in case the value doesn't exist in the source.
Wisely stands for based on the "Country" value of both dataframes.
"""
countries = df["Country"].unique().tolist()
for country in countries:
#a, b, c = colname, country, source_df.loc[ source_df["Country"] == country, source_col].values
#print(f"Feature {a} inserting country {b} value {c}")
if country in source_df["Country"].tolist():
df.loc[ df["Country"] == country, colname ] = \
source_df.loc[ source_df["Country"] == country, source_col].values
else:
df.loc[ df["Country"] == country, colname ] = default
# return df
def fill_df_column_date_based(df, colname, source_df, default):
"""Takes the specified column from the source dataframe and inserts its data
wisely in the specified column of the target dataframe. It admits a default
value in case the value doesn't exist in the source.
Wisely stands for based on the "Country" value of both dataframes, and
matching the dates in source and target.
For those dates where no value is specified in the source, the latest value
is kept.
"""
countries = df["Country"].unique().tolist()
for country in countries:
if country in source_df["Country"].tolist():
data = source_df.loc[ source_df["Country"] == country].T.values
# Extend the latest value up to the lenght needed
lenght_difference = len(df[df["Country"] == country]) - len(data)
#from IPython import embed
#embed()
# Extend
data = data.tolist() + [data[-1].tolist()] * (lenght_difference+1)
# If we have further data than needed, should cut
if (lenght_difference+1) < 0:
data = data[:(lenght_difference+1)]
# Remove the country name at the beginning
data = data[1:]
df.loc[ df["Country"] == country, colname ] = data
else:
df.loc[ df["Country"] == country, colname ] = default
def clean_invalid_data(df):
"""Removes those samples in the dataframe where current and next day cases
are 0
"""
# Removing samples with 0 cases in previous day
mask = df["Cases"]!=0
df = df.loc[mask]
# Removing samples with 0 cases next day
mask = df["NextDay"]!=0
df = df.loc[mask]
# Removing samples with same amount on both days
mask = df["NextDay"] != df["Cases"]
df = df.loc[mask]
# Let's ensure there're not object type columns
df = df.infer_objects()
return df
def normalize_data(df, norm_cases=True, bias=0):
"""Normalizes the data from numeric columns in the dataframe. Allows
to set a bias to add after normalization.
Takes into account that Cases and NextDay should be normalized by using
log.
"""
same = ["Cases", "NextDay"]
same_max = 0
for col in df.columns:
if np.issubdtype(df[col].dtype, np.number):
if col in same:
same_max = max(same_max, df[col].max())
else:
max_val = df[col].max()
df.loc[:, col] = (df.loc[:, col] / max_val) + bias
# Normalize the cases cols
if norm_cases:
col = same[0]
df.loc[:, col] = np.log(df.loc[:, col])
col = same[1]
df.loc[:, col] = np.log(df.loc[:, col])
return df