Numpy读写CSV文件。CSV文件:通过逗号分隔的文本文件。
读写CSV文件实例:
from numpy import *
a = arange(20).reshape(4,5)
print(a)
#delimiter:分隔符属性,指定以什么字符分隔;对一维数组不起作用
savetxt('a.txt',a,fmt='%d',delimiter=',')#以逗号,分隔
#usecols:指定获取对应的列数的数据
b = loadtxt('a.txt',dtype=int,delimiter=',',usecols=(1,3,4))
print(b)
#unpack:将usecols属性指定获取对应的列数的数据,分别存入到左侧的变量中
x,y,z = loadtxt('a.txt',dtype=int,delimiter=',',usecols=(1,3,4),unpack=True)
print(x)
print(y)
print(z)
输出结果:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
[[ 1 3 4]
[ 6 8 9]
[11 13 14]
[16 18 19]]
[ 1 6 11 16]
[ 3 8 13 18]
[ 4 9 14 19]
a.txt文件内容是: