Search code examples
pythonnumpymatplotlibglob

ValueError: Could not convert string to float: "nbformat":4


After some long calculation, I've got files which contain following strings.

(Each string is separated with "\t" and has "\n" at the end of the each line.)

0.0000008375000 829.685601736   555.939928236
0.0000008376000 829.511081539   555.889353246
0.0000008377000 829.336613968   555.838785601
0.0000008378000 829.162199002   555.7882253
0.0000008379000 828.987836621   555.737672342
0.0000008380000 828.813526805   555.687126727
0.0000008381000 828.639269533   555.636588453

Then I tried to plot these files. (The file's name is starting with P.)

fList = np.array(gl.glob("P*"))
for i in fList:
    f = open(i, "r")
    data = f.read()
    data = data.replace("\n", "\t")
    data = np.array(data.split("\t"))[:-1].reshape(-1,3)
    plt.plot(data[:,0], data[:,1], label=i)

Then I ended up with following error.

(Error pointer indicates this happened at the line plt.plot(data[:,0], data[:,1], label=i))

ValueError: could not convert string to float: "nbformat": 4,

I've looked up some other tutorials or walkthroughs but unfortunately, could not understand how to fix this issue. Any help or advice would be very grateful.


Solution

  • You can directly use numpy to read in the file into three arrays:

    import numpy as np
    import matplotlib.pyplot as plt
    from glob import glob
    
    fList = glob("P*")
    for i in fList:
        x,y,z = np.loadtxt(i, unpack=True)
        plt.plot(x,y, label=i)
    
    plt.legend()
    plt.show()