2.2。数据预处理
2.2.1。读取数据集
例如,我们首先创建一个人工数据集,该数据集存储在csv(逗号分隔值)文件中../data/house_tiny.csv
。以其他格式存储的数据可以用类似的方式处理。以下 mkdir_if_not_exist
功能确保该目录../data
存在。注释是一个特殊标记,其中以下函数,类或import语句也保存在包中,以便我们以后可以直接调用 。
# Saved in the d2l package for later use
d2l
d2l.mkdir_if_not_exist()
import os # Saved in the d2l package for later use def mkdir_if_not_exist(path): if not isinstance(path, str): path = os.path.join(*path) if not os.path.exists(path): os.makedirs(path)
下面,我们将数据集逐行写入csv文件。
data_file = '../data/house_tiny.csv' mkdir_if_not_exist('../data') with open(data_file, 'w') as f: f.write('NumRooms,Alley,Price\n') # Column names f.write('NA,Pave,127500\n') # Each row is a data point f.write('2,NA,106000\n') f.write('4,NA,178100\n') f.write('NA,NA,140000\n')
为了从创建的csv文件加载原始数据集,我们导入 pandas
包并调用该read_csv
函数。该数据集具有44 行和 33 列,每行描述房间的the number of rooms (“NumRooms”), the alley type (“Alley”), and the price (“Price”
# If pandas is not installed, just uncomment the following line: # !pip install pandas import pandas as pd data = pd.read_csv(data_file) print(data)
NumRooms Alley Price 0 NaN Pave 127500 1 2.0 NaN 106000 2 4.0 NaN 178100 3 NaN NaN 140000