Python--numpy(np.loadtxt)

来源:互联网 发布:mysql字段不区分大小写 编辑:程序博客网 时间:2024/05/19 01:59

本文参考:http://blog.csdn.net/u010025211/article/details/51498790

import numpy as np

np.loadtxt 

       作用是把文本文件(*.txt)读入并以矩阵或向量的形式输出。它有几个参数:skiprows,delimiter,usecoles和unpack。skiprows作用是跳过头行。在默认情况下是通过空格来分割列的,如果想通过其他来分割列则需要通过delimiter来设置。如果你想跳过几列来读取则需要用usecoles来设置。

        正常情况下该返回的是二维矩阵,若设置了unpack=True将返回各列。例子如下:

1.全是数字的

                                                                               

 >>> np.loadtxt(loadtxt.txt')                                                               >>> np.loadtxt('loadtxt.txt', skiprows=1,delimiter=',')                 
array([[ 1.,  2.,  3.,  4.],                                                                               array([[ 4.,  7.,  5.,  9.],                                                                   
       [ 4.,  7.,  5.,  9.],                                                                                              [ 7.,  2.,  2.,  2.]])
       [ 7.,  2.,  2.,  3.]])

>>> np.loadtxt('loadtxt.txt', skiprows=1)
array([[ 4.,  7.,  5.,  9.],
       [ 7.,  2.,  2.,  3.]])

                                                                                                        

>>> np.loadtxt('loadtxt.txt',unpack=True)                               >>> np.loadtxt('loadtxt.txt',delimiter='\t')                            >>> np.loadtxt('loadtxt.txt',delimiter=',',usecols=[1,2,3][)
array([[ 1.,  4.,  3.],    array([ 1.,  4.,  7.])array([[ 2.,  3.,  5.], 

   [ 2.,  7.,  8.],        [ 5.,  6.,  6.],

   [ 3.,  2.,  9.]])   [ 5.,  6.,  8.],   

>>> a,b,c=np.loadtxt('loadtxt.txt',unpack=True)                                                                                                                                         [ 7.,  9.,  0.],  

 >>> a                [8.,  0.,  8.,]

array([ 1.,  4.,  3.]) >>> np.loadtxt('loadtxt.txt',delimiter=',',usecols=(0,3,4))

>>> b                                                                            array([[ 1.,  5.,  8.],
array([ 2.,  7.,  8.])                                                     [ 4.,  6.,  7.],
>>> c                           [ 1.,  8.,  9.],

array([ 3.,  2.,  9.])                                                                                                                                                                                      [ 8.,  0.,  5.],                       

                                                                   [ 8.,  8.,  1.]])


2.含字母


>>> a,b,c=np.loadtxt('loadtxt.txt',str,unpack=True)
>>> a
'k,l,g'
>>> np.loadtxt('loadtxt.txt',str,unpack=True)
array(['k,l,g', 'gan,j,k', 'j,u,o'], 
      dtype='|S7')
>>> np.loadtxt('loadtxt.txt',str)
array(['k,l,g', 'gan,j,k', 'j,u,o'], 
      dtype='|S7')
>>> np.loadtxt('loadtxt.txt',str,delimiter=',')
array([['k', 'l', 'g'],
       ['gan', 'j', 'k'],
       ['j', 'u', 'o']], 
      dtype='|S3')





1 0
原创粉丝点击