代码之家  ›  专栏  ›  技术社区  ›  hatmatrix

如何将CSV数据读入NumPy中的记录数组?

  •  332
  • hatmatrix  · 技术社区  · 15 年前

    我想知道是否有一种直接的方法将CSV文件的内容导入到一个记录数组中,就像R read.table() , read.delim() ,和 read.csv()

    还是最好的使用方法 csv.reader() numpy.core.records.fromrecords() ?

    10 回复  |  直到 7 年前
        1
  •  731
  •   Mike Graham    14 年前

    你可以用Numpy的 genfromtxt() 方法,通过设置 delimiter

    from numpy import genfromtxt
    my_data = genfromtxt('my_file.csv', delimiter=',')
    

    有关该函数的更多信息,请参见相应的 documentation

        2
  •  203
  •   Community Mohan Dere    8 年前

    我推荐 read_csv pandas 图书馆:

    import pandas as pd
    df=pd.read_csv('myfile.csv', sep=',',header=None)
    df.values
    array([[ 1. ,  2. ,  3. ],
           [ 4. ,  5.5,  6. ]])
    

    DataFrame -允许 many useful data manipulation functions which are not directly available with numpy record arrays

    DataFrame是一种二维标记的数据结构,包含 可能是不同的类型。你可以把它想象成电子表格或者 SQL表。。。


    我也建议 genfromtxt . 然而,既然这个问题要求 record array ,与普通数组相反 dtype=None 参数需要添加到 电话:

    给定一个输入文件, myfile.csv :

    1.0, 2, 3
    4, 5.5, 6
    
    import numpy as np
    np.genfromtxt('myfile.csv',delimiter=',')
    

    给出一个数组:

    array([[ 1. ,  2. ,  3. ],
           [ 4. ,  5.5,  6. ]])
    

    np.genfromtxt('myfile.csv',delimiter=',',dtype=None)
    

    给出一个记录数组:

    array([(1.0, 2.0, 3), (4.0, 5.5, 6)], 
          dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<i4')])
    

    multiple data types (including strings) can be easily imported .

        3
  •  83
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    我计时了

    from numpy import genfromtxt
    genfromtxt(fname = dest_file, dtype = (<whatever options>))
    

    import csv
    import numpy as np
    with open(dest_file,'r') as dest_f:
        data_iter = csv.reader(dest_f,
                               delimiter = delimiter,
                               quotechar = '"')
        data = [data for data in data_iter]
    data_array = np.asarray(data, dtype = <whatever options>)
    

    在460万行(约70列)上,发现NumPy路径耗时2分16秒,csv列表理解方法耗时13秒。

        4
  •  67
  •   jkmartindale David Nouls    5 年前

    你也可以试试 recfromcsv() 它可以猜测数据类型并返回格式正确的记录数组。

        5
  •  18
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    • 更快
    • 减少CPU使用
    • 与NumPy genfromtxt相比,使用了1/3的RAM

    $ for f in test_pandas.py test_numpy_csv.py ; do  /usr/bin/time python $f; done
    2.94user 0.41system 0:03.05elapsed 109%CPU (0avgtext+0avgdata 502068maxresident)k
    0inputs+24outputs (0major+107147minor)pagefaults 0swaps
    
    23.29user 0.72system 0:23.72elapsed 101%CPU (0avgtext+0avgdata 1680888maxresident)k
    0inputs+0outputs (0major+416145minor)pagefaults 0swaps
    

    测试数量_csv.py文件

    from numpy import genfromtxt
    train = genfromtxt('/home/hvn/me/notebook/train.csv', delimiter=',')
    

    from pandas import read_csv
    df = read_csv('/home/hvn/me/notebook/train.csv')
    

    du -h ~/me/notebook/train.csv
     59M    /home/hvn/me/notebook/train.csv
    

    NumPy和pandas的版本:

    $ pip freeze | egrep -i 'pandas|numpy'
    numpy==1.13.3
    pandas==0.20.2
    
        6
  •  7
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    import numpy as np
    csv = np.genfromtxt('test.csv', delimiter=",")
    print(csv)
    
        7
  •  6
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    我建议用桌子( pip3 install tables ). 你可以省下你的钱 .csv 文件到 .h5 pip3 install pandas

    import pandas as pd
    data = pd.read_csv("dataset.csv")
    store = pd.HDFStore('dataset.h5')
    store['mydata'] = data
    store.close()
    

    然后,您就可以轻松地、用更少的时间(即使是处理大量数据)将数据加载到 NumPy阵列

    import pandas as pd
    store = pd.HDFStore('dataset.h5')
    data = store['mydata']
    store.close()
    
    # Data in NumPy format
    data = data.values
    
        8
  •  5
  •   Guillaume Jacquenot mbernasocchi    7 年前

    使用 numpy.loadtxt

    很简单的方法。但它要求所有元素都是float(int等)

    import numpy as np 
    data = np.loadtxt('c:\\1.csv',delimiter=',',skiprows=0)  
    
        9
  •  5
  •   Kermit    5 年前

    这是最简单的方法:

    import csv
    with open('testfile.csv', newline='') as csvfile:
        data = list(csv.reader(csvfile))
    

        10
  •  4
  •   Hamid Rouhani Pierre-Antoine LaFayette    8 年前

    我试过这个:

    import pandas as p
    import numpy as n
    
    closingValue = p.read_csv("<FILENAME>", usecols=[4], dtype=float)
    print(closingValue)
    
        11
  •  4
  •   Butiri Dan    6 年前

    import csv
    with open("data.csv", 'r') as f:
        data = list(csv.reader(f, delimiter=";"))
    
    import numpy as np
    data = np.array(data, dtype=np.float)
    
        12
  •  0
  •   kdurant    5 年前
    In [329]: %time my_data = genfromtxt('one.csv', delimiter=',')
    CPU times: user 19.8 s, sys: 4.58 s, total: 24.4 s
    Wall time: 24.4 s
    
    In [330]: %time df = pd.read_csv("one.csv", skiprows=20)
    CPU times: user 1.06 s, sys: 312 ms, total: 1.38 s
    Wall time: 1.38 s