创建包含更多行和列的原始数据集
import torch
import os
os.makedirs(os.path.join('..','data'),exist_ok=True)
data_file = os.path.join('..','data','nba_data.csv')
with open(data_file,'w') as f:
f.write('Points,Rebound,Assist,Steal,Blocks,Turnovers\n')
f.write('81,10,10,1,2,NA\n')
f.write('NA,NA,12,3,NA,5\n')
f.write('20,NA,NA,2,NA,2\n')
f.write('100,NA,2,NA,2,NA\n')
f.write('30,2,8,2,NA,5\n')
import pandas as pd
data = pd.read_csv(data_file)
1. 删除缺失值最多的列
法1:
data.isnull().sum()
#查询各个列的缺失值个数
data.isnull().sum().idxmax()
#idxmax()函数返回请求轴上第一次出现最大值的索引名
data.drop(data.isnull().sum().idxmax(),axis=1)
#drop()函数删除最大缺失值个数的列
法2:
#定义drop_col删除列函数
def drop_col(m):
num = m.isna().sum()
#获得缺失值统计信息
num_dict = num.to_dict()
#转为字典
max_key = max(num_dict,key=num_dict.get)
#取字典中最大值的键
del m[max_key]
#删除缺失值最多的列
return m
drop_col(data)
#调用drop_col函数删除缺失值最多的列
2. 将预处理的数据集转为张量格式
output = data.drop(data.isnull().sum().idxmax(),axis=1)
#定义output存储法1中删除缺失值最多的列后的数据集
x = torch.tensor(output.values)
#将数据集转换为张量格式
参考b站教程:《动手学深度学习 v2 - 从零开始介绍深度学习算法和代码实现》
课程主页:https://courses.d2l.ai/zh-v2/