Loading a file into a numpy array with python

后端 未结 5 1174
庸人自扰
庸人自扰 2020-12-14 04:44

So I\'m very green with Python and am trying to learn by replicating some matlab code I\'ve written. I have a part where, in matlab, I load a data file that\'s tab-delimited

5条回答
  •  天涯浪人
    2020-12-14 05:48

    If you're using Python for MATLAB-like purposes you're going to want to be using NumPy (and scipy); in particular, you should read NumPy for MATLAB Users.

    If you have comma-delimited data, you can use numpy.loadtxt to read it (after installing numpy, of course):

    $ cat matrix.csv 
    1,2,3
    4,5,6
    7,8,9
    

    and then

    >>> import numpy as np
    >>> m = np.loadtxt("matrix.csv", delimiter=",")
    >>> m
    array([[ 1.,  2.,  3.],
           [ 4.,  5.,  6.],
           [ 7.,  8.,  9.]])
    >>> np.matrix(m)
    matrix([[ 1.,  2.,  3.],
            [ 4.,  5.,  6.],
            [ 7.,  8.,  9.]])
    

提交回复
热议问题