Python之Numpy实践笔记(3)

读写文件

使用savetxt函数将数据存储到文件中,需要指定文件名以及保存的数组

importnumpyasnp

i2 = np.eye(2)#2*2单位矩阵

np.savetxt("eye.txt",i2)

loadtxt函数读取csv文件,自动切分字段,并将数组载入NumPy数组

以苹果公司的历史股价数据csv文件为例:(只显示部分)

AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800

AAPL,31-01-2011, ,335.8,340.04,334.3,339.32,13473000

AAPL,01-02-2011, ,341.3,345.65,340.98,345.03,15236800

AAPL,02-02-2011, ,344.45,345.25,343.55,344.32,9242600

AAPL,03-02-2011, ,343.8,344.24,338.55,343.44,14064100

AAPL,04-02-2011, ,343.61,346.7,343.51,346.5,11494200

AAPL,07-02-2011, ,347.89,353.25,347.64,351.88,17322100

AAPL,08-02-2011, ,353.68,355.52,352.15,355.2,13608500

AAPL,09-02-2011, ,355.19,359,354.87,358.16,17240800

AAPL,10-02-2011, ,357.39,360,348,354.54,33162400

AAPL,11-02-2011, ,354.75,357.8,353.54,356.85,13127500

AAPL,14-02-2011, ,356.79,359.48,356.71,359.18,11086200

AAPL,15-02-2011, ,359.19,359.97,357.55,359.9,10149000

AAPL,16-02-2011, ,360.8,364.9,360.5,363.13,17184100

AAPL,17-02-2011, ,357.1,360.27,356.52,358.3,18949000

AAPL,18-02-2011, ,358.21,359.5,349.52,350.56,29144500

AAPL,22-02-2011, ,342.05,345.4,337.72,338.61,31162200

AAPL,23-02-2011, ,338.77,344.64,338.61,342.62,23994700

AAPL,24-02-2011, ,344.02,345.15,338.37,342.88,17853500

AAPL,25-02-2011, ,345.29,348.43,344.8,348.16,13572000

AAPL,28-02-2011, ,351.21,355.05,351.12,353.21,14395400

AAPL,01-03-2011, ,355.47,355.72,347.68,349.31,16290300

AAPL,02-03-2011, ,349.96,354.35,348.4,352.12,21521000

AAPL,03-03-2011, ,357.2,359.79,355.92,359.56,17885200

AAPL,04-03-2011, ,360.07,360.29,357.75,360,16188000

只关注最后两列: 收盘价和成交量 ,将这两项数据分别载入到两个数组中

importnumpyasnp

c,v = np.loadtxt('data.csv',delimiter=',',unsecols= (6,7),unpack=True)

printc

printv

在这里设置分割符为 ,(逗号)unsecols参数为一个元组,获取第7列和第8列的数据(最后两列),unpack=true意为分拆存储不同列的数据(分别将收盘价和成交量的数组赋值给变量c,v)

结果:

[ 336.1339.32345.03344.32343.44346.5351.88355.2358.16

354.54356.85359.18359.9363.13358.3350.56338.61342.62

342.88348.16353.21349.31352.12359.56360.355.36355.76

352.47346.67351.99]

[ 21144800.13473000.15236800.9242600.14064100.11494200.

17322100.13608500.17240800.33162400.13127500.11086200.

10149000.17184100.18949000.29144500.31162200.23994700.

17853500.13572000.14395400.16290300.21521000.17885200.

16188000.19504300.12718000.16192700.18138800.16824200.]

numpy.loadtxt

numpy.loadtxt(fname,dtype=,comments='#',delimiter=None,converters=None,skiprows=0,usecols=None,unpack=False,ndmin=0)[source]

http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html

你可能感兴趣的:(Python之Numpy实践笔记(3))