常用数据文件内容格式如下
10,张三,22,男,172,57,95
11,李四,25,男,180,65,90
12,王红,23,女,160,50,99
从该文本数据可以看出,一般为:
一行一样本,一列一特征,每个特征之间用特殊字符(如逗号,空格)分割;
1 csv 文件
csv文件:逗号分割值文件 -numpy.loadtxt-> 二维数组
numpy.loadtxt( 文件路径, delimiter=分隔符, usecols=(列索引序列), unpack=是否用指定的类型做类型转换, dtype=指定目标类型(缺省为浮点数类型), converters={列索引: 转换函数, ...})->列数组集合
将aapl.csv 以文本形式打开
长短不一,为了更好地显示,用 excel 格式打开内容
并采用下段代码读取其中内容
dates, open_prices, high_prices,\ low_prices, close_prices = np.loadtxt( './aapl.csv', delimiter=',', usecols=(1, 3, 4, 5, 6), unpack=True, dtype=np.dtype('M8[D], f8, f8, f8, f8'), converters={1: dmy2ymd}) # 自定义的转换函数 # 1: dmy2ymd 表示usecols中的1调用dmy2ymd转换函数 # np.loadtxt 获得的是列数组集合 # dates, open_prices,等是获取列数据
附:读取文件并show,
import datetime as dt import numpy as np import matplotlib.pyplot as mp import matplotlib.dates as md def dmy2ymd(dmy): dmy = str(dmy, encoding='utf-8') date = dt.datetime.strptime(dmy, '%d-%m-%Y').date() ymd = date.strftime('%Y-%m-%d') return ymd dates, opening_prices, highest_prices,\ lowest_prices, closing_prices = np.loadtxt( './aapl.csv', delimiter=',', usecols=(1, 3, 4, 5, 6), unpack=True, dtype=np.dtype('M8[D], f8, f8, f8, f8'), converters={1: dmy2ymd}) print(dates) mp.figure('Candlestick', facecolor='lightgray') mp.title('Candlestick', fontsize=20) mp.xlabel('Date', fontsize=14) mp.ylabel('Price', fontsize=14) ax = mp.gca() ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO)) ax.xaxis.set_minor_locator(md.DayLocator()) ax.xaxis.set_major_formatter(md.DateFormatter('%d %b %Y')) mp.tick_params(labelsize=10) mp.grid(linestyle=':') dates = dates.astype(md.datetime.datetime) rise = closing_prices - opening_prices >= 0.01 fall = opening_prices - closing_prices >= 0.01 fc = np.zeros(dates.size, dtype='3f4') ec = np.zeros(dates.size, dtype='3f4') fc[rise], fc[fall] = (1, 1, 1), (0, 0.5, 0) ec[rise], ec[fall] = (1, 0, 0), (0, 0.5, 0) mp.bar(dates, highest_prices - lowest_prices, 0, lowest_prices, color=fc, edgecolor=ec) mp.bar(dates, closing_prices - opening_prices, 0.8, opening_prices, color=fc, edgecolor=ec) mp.gcf().autofmt_xdate() mp.show()