【问题标题】:Write numpy array to csv file with a specific number of columns将numpy数组写入具有特定列数的csv文件
【发布时间】:2015-08-20 08:10:23
【问题描述】:

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

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

我使用fmt="%s" 选项,因为在每一行的末尾(数组的第 444 个元素是NaN)。

我想要完成的是编写一个 5 列宽的 csv 文件,总共 39,516 行(即 89 个部分,每个部分由 5 列和 444 行组成),最后是 @987654327 @ 写为第 444 行末尾的空元素。这样一来,矩阵的元素数量相等: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,

我添加了行号以便在我的问题中更清楚。我不希望它出现在实际输出中。

什么是一种高效且 Pythonic 的方式?

目前,我正在尝试根据我的情况调整这个问题的答案:

Write to list to rows with specific number of columns.

【问题讨论】:

  • 我不明白。你想要 444 个单独的 csv 文件吗?
  • @RickTeachey 很好,在某种程度上是的。因为 5 列乘以 89 行是 444。我尝试将数组重塑为 (89,5,444) 但 np.savetxt 并没有给我我需要的东西。
  • 如果您的数组的形状为 444x445,则有 197,580 条数据。如果我理解,您想要的是一个 39,516 行(有 5 列)长的 csv 文件,对吗?第 89 行、第 178 行等将以“nan”结尾。对吗?
  • @RickTeachey 是正确的。
  • 其实第89行、第178行等不应该以'nan'结尾,而是少一个元素。我认为这不能通过调用numpy.savetxt() 来实现。使用掩码数组,您可以获得类似xxxx,xxxx,, 的内容,即不是一行少一个元素,而是一行空元素。

标签: python csv numpy


【解决方案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 不能用于二维以上的 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'] = ''
  • 还有reshape。我非常喜欢您的解决方案,但是当您尝试在没有 nan 的情况下保存 .astype(str) 数组时 -> `TypeError: float argument required, not numpy.ndarray`。
  • @muammar,我意识到保存具有 (a,b,c) 形状的 numpy 数组存在问题。查看编辑并告诉我它是否有效或者您想要自定义它
  • 要保存到磁盘,fmt 必须设置为fmt='%s',否则会失败。非常感谢您的帮助。我会将您的解决方案标记为正确答案。
  • 这是我的荣幸,伙计 =)
猜你喜欢
  • 2023-03-31
  • 2019-04-09
  • 2014-08-30
  • 2016-09-27
  • 1970-01-01
  • 2021-04-21
  • 2012-06-07
  • 2015-12-13
  • 2017-01-04
相关资源
最近更新 更多