简体   繁体   English

将 dtype=object numpy arrays 保存在包含浮点数和字符串的 csv 文件中

[英]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.我必须在 CSV 文件的每一行中保存 3 个字符串和一个浮点数。 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?如何将 NumPy 数组中的此类混合变量保存到 CSV 文件中?

You want to specify a fmt string to np.savetxt , like this:您想为np.savetxt指定一个fmt字符串,如下所示:

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). NB 似乎您想要 append 您的数据逐行,在这种情况下,您需要重塑以将您的数据放入列(一行)。 The fmt string should match the number of columns you want to specify. fmt字符串应与您要指定的列数匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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