Search code examples
pythonlistnumpygenfromtxt

Read several lists from the text file properly python


I have a text file which have 541 lists and each list has 280 numbers such as below:

[301.82779832839964, 301.84247725804647, 301.85718673070272, ..., 324.4056396484375, 324.20379638671875, 324.00198364257812]
                                   .
                                   .
[310.6907599572782, 310.68334604280966, 310.67756809346469,..., 324.23541883368551, 324.18277040240207, 324.09177971086382]

To read this text file, I used numpy.genfromtxt making a code to read the first list for the test such as:

pt1 = np.genfromtxt(filn1,dtype=np.float64,delimiter=",")
print pt1[0].shape
print list(pt1[0])

I expected that I could see the full list of the first list but the result list showed 'nan' in the first and the last place as below:

[nan, 301.84247725804647, 301.85718673070272, ...,  324.4056396484375, 324.20379638671875, nan]

I have tried other option in numpy.genfromtxt, I couldn't find why it resulted 'nan' in the first and the last place in the list. This event was not only for the first list, but also for all lists.

Any idea or help would be really appreciated.

Thank you,

Isaac


Solution

  • import numpy as np
    from ast import literal_eval
    pt1 = np.array(map(literal_eval,open("in.txt")))
    

    For:

    [301.82779832839964, 301.84247725804647, 301.85718673070272,  324.4056396484375, 324.20379638671875, 324.00198364257812]
    [310.6907599572782, 310.68334604280966, 310.67756809346469, 324.23541883368551, 324.18277040240207, 324.09177971086382]
    

    You will get:

    [[ 301.82779833  301.84247726  301.85718673  324.40563965  324.20379639
       324.00198364]
     [ 310.69075996  310.68334604  310.67756809  324.23541883  324.1827704
       324.09177971]]