使用特定列数将numpy数组写入csv文件

3

我有一个形状为(444,445)的numpy数组,我需要将其转储为csv文件。可以通过以下方式实现:

np.savetxt('outfile.txt',array, delimiter=',',fmt="%s")

我使用fmt="%s"选项,因为在数组的每一行末尾(即第444个元素),都是NaN
我想要实现的是写入一个有5列、共39,516行的csv文件(也就是89个部分,每个部分由5列和444行组成),最后在第444行的末尾将NaN写入为空元素。这样,矩阵中的元素数量相当:89x5x444=444x445,即197,580个数据点。
例如:
  1 xxxx,xxxx,xxxx,xxxx,xxxx,
  2 xxxx,xxxx,xxxx,xxxx,xxxx,
    ...
    ...
 89 xxxx,xxxx,xxxx,xxxx,
 90 xxxx,xxxx,xxxx,xxxx,xxxx,
 91 xxxx,xxxx,xxxx,xxxx,xxxx,
    ...
    ...
178 xxxx,xxxx,xxxx,xxxx,

我在我的问题中添加了行号,以便更清楚。但实际输出中不需要它。

有什么高效且符合Python风格的方法可以做到这一点?

目前,我正在尝试将此问题的答案适应到我的情况:

将列表写入特定列数的行中.


我不明白。你是想要444个单独的csv文件吗? - Rick
1
@RickTeachey 那是正确的。 - muammar
1
实际上,第89行、第178行等不应以“nan”结尾,而应该少一个元素。我认为这不能通过单个对numpy.savetxt()的调用来实现。使用掩码数组,您可以获得类似于xxxx,xxxx,,的内容,即不是一行少一个元素,而是一行有一个空元素。 - Stefano M
你应该做的一件事是尝试自己编写实际代码。它不必太多,但应该是一个坚实的“第一次尝试”。这样你更有可能得到好的答案。 - Rick
@StefanoM 再次阅读后,我确实发现你是对的。 - Rick
显示剩余4条评论
1个回答

1
希望我能够正确理解您的要求。
# Reshape it

array_.reshpe(89,444,5)

# Change it's dtype to str so you can replace NaN by white spaces

array_.astype(str)

# Replace nan by white spaces

array_[array_ == 'nan'] = ''


# Finaly, save it SEE EDIT

编辑

我认为np.savetxt无法处理超过2维的numpy数组,所以,参考this answer,我们可以尝试这样做:

# Write the array to disk
with file('test.txt', 'w') as outfile:
    # I'm writing a header here just for the sake of readability
    # Any line starting with "#" will be ignored by numpy.loadtxt
    outfile.write('# Array shape: {0}\n'.format(array_.shape))

    # Iterating through a ndimensional array produces slices along
    # the last axis. This is equivalent to array_[i,:,:] in this case
    for data_slice in array_:

        # The formatting string indicates that I'm writing out
        # the values in left-justified columns 7 characters in width
        # with 2 decimal places.  
        np.savetxt(outfile, data_slice, fmt='%-7.2f')

        # Writing out a break to indicate different slices...
        outfile.write('# New slice\n')

抱歉 @muammar,它的意思是 array_[array_ == 'nan'] = '' - farhawa
还有reshape。我非常喜欢你的解决方案,但是当你尝试在没有nan的情况下保存.astype(str)数组时,会出现TypeError: float argument required, not numpy.ndarray错误。 - muammar
@muammar,我意识到保存一个形状为(a,b,c)的numpy数组存在问题。看一下编辑后的内容,告诉我它是否有效或者你想要自定义它。 - farhawa
为了保存到磁盘中,fmt 必须设置为 fmt='%s',否则会失败。非常感谢您的帮助。我会将您的解决方案标记为正确答案。 - muammar
很高兴为你效劳,老兄 =) - farhawa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接