简体   繁体   中英

Save dtype=object numpy arrays in a csv file containing floats and strings

I must save 3 strings and one float in each line of a CSV file. Here is what I did:

    filename = "results.txt"
    if os.path.exists(filename):
        append_write = "a"
    else:
        append_write = "w"
    
    #I am saving 3 strings and one float, they come from a numpy array 
    results = np.array(["a", "b", "c", 0.32],dtype=object)
    
    f = open(filename, append_write)
    np.savetxt(f, results, delimiter=",")
    f.close()

However, here is the error I get whenever I run such a code

  raise TypeError("Mismatch between array dtype ('%s') and "
  TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')

How can I save such mixed variables in a NumPy array to a CSV file?

You want to specify a fmt string to np.savetxt , like this:

results = np.array(["a", "b", "c", 0.32], dtype=object).reshape(1, -1)
fmt = '%s,%s,%s,%f'

with open(filename, append_write) as f:
    np.savetxt(f, results, delimiter=",", fmt=fmt)

NB It seems like you want to append your data row-wise, in which case, you need the reshape to get your data into columns (into one row). The fmt string should match the number of columns you want to specify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM