import urllib.request import requests from io import StringIO import numpy as np import pandas as pd ''' 下载网络文件,并导入CSV文件作为numpy的矩阵 ''' # 网络数据文件地址 url = "http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" # 方法一 # ======================================================== # 下载文件 #r = urllib.request.urlopen(url) # 导入CSV文件作为numpy的矩阵 #dataset = np.loadtxt(r, delimiter=",") # 方法二 # ======================================================== # 下载文件 #r = requests.get(url) # 导入CSV文件作为numpy的矩阵 #dataset = np.loadtxt(StringIO(r.text), delimiter=",") # 此处用到 StringIO !!!!!! # 方法三 # ======================================================== #用genfromtxt直接下载网络文件,并将CSV文件导作numpy矩阵。爽!!!!!!!! #dataset = np.genfromtxt(url, delimiter=",") # 方法四 # ======================================================== # 用pandas.read_csv直接下载网络文件,并将CSV文件导作pandas.DataFrame。 # dataset = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0) dataset = pd.read_csv(url) # ======================================================== # separate the data from the target attributes X = dataset[:,0:7] y = dataset[:,8] print(X) #print(y)