生データを読み取り、処理する
このステップでは、raw_data.csv
ファイルから生データを読み取り、各行を処理して、有効な行を clean_data
リストに追加します。
data_clean.py
ファイルで、clean_data
リストの初期化の下に次のコードを追加します。
## Open and read the raw data CSV file
with open("raw_data.csv", "r") as f:
reader = csv.DictReader(f) ## Use DictReader for easy access to columns by name
for row in reader:
## Extract relevant fields from each row
name = row["name"]
sex = row["gender"]
date = row["birth date"]
mail = row["mail"]
## Check if the name field is empty and skip the row if it is
if len(name) < 1:
continue
## Check if the gender field is valid (either 'M' or 'F') and skip the row if not
if sex not in ["M", "F"]:
continue
## Attempt to parse the birth date and calculate age; skip the row if parsing fails
try:
date = datetime.strptime(date, "%Y-%m-%d")
except ValueError:
continue
age = datetime.now().year - date.year
## Skip the row if the calculated age is unrealistic (less than 0 or more than 200)
if age < 0 or age > 200:
continue
## Define a regex pattern for validating email addresses
r = r"^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}$"
## Check if the email field matches the regex pattern and skip the row if it doesn't
if not re.match(r, mail):
continue
## If all checks pass, append the row to the cleaned data list
clean_data.append(row)
このコードは、raw_data.csv
ファイルから生データを読み取り、各行を処理して、有効な行を clean_data
リストに追加します。