[英]Exporting each row of a 2D numpy array as a single element in csv column
I have a 2D numpy array which has a shape of (15015,262). 我有一个二维(numpy)数组,其形状为(15015,262)。 I need to export it to a csv file so that each row of the numpy 2Darray is a single element list of the csv file (ie, the csv file should have a shape of (15015,1). 我需要将其导出到一个csv文件,以便numpy 2Darray的每一行都是该csv文件的单个元素列表 (即,该csv文件的形状应为(15015,1)。
I tried using the csv modules of python and the numpy modules but nothing seems to work properly. 我尝试使用python和numpy模块的csv模块,但似乎没有任何正常工作。 For example, I tried using 例如,我尝试使用
with open('filename.csv', 'wb') as f: writer = csv.writer(f) for val in modified_seq_data: writer.writerow([val])
In the above case (even though the csv file does get saved in a single column), when I call it back via np.genfromtxt (for a different code) I get the following output: 在上述情况下(即使csv文件确实保存在单列中),当我通过np.genfromtxt(针对不同的代码)进行调用时,也会得到以下输出:
[nan nan nan nan nan ..... nan nan nan]
Somehow it is not able to export the csv into a numpy 1D array where each element is a list. 不知何故,它无法将csv导出到每个元素都是列表的numpy 1D数组中。 Any help will be much appreciated! 任何帮助都感激不尽!
Assuming that modified_seq_data
is the numpy array: 假设modified_seq_data
是numpy的数组:
with open('filename.csv', 'wb') as f:
writer = csv.writer(f)
for i in range(modified_seq_data.shape[0]):
writer.writerow([modified_seq_data[i, :]])
Does your single output list object have commas in it? 您的单个输出列表对象中是否包含逗号? If so, your reader could just be reading into those commas through the list. 如果是这样,您的读者可能只是通过列表阅读了这些逗号。 As far as the structure goes, which I think is the underlying issue here, you need 1 atomic value in each row to get the effect of the csv. 就结构而言,我认为这是根本问题,每行需要1个原子值才能获得csv的效果。 So I would consider casting your list object into a big string separated by spaces, writing that out, then reading it in, splitting it, and casting the type back to what it is needed to be. 因此,我考虑将您的列表对象转换为由空格分隔的大字符串,将其写出,然后读入,拆分,然后将类型转换回所需的值。
Hope this helps. 希望这可以帮助。 BC 公元前
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.