【问题标题】:Python 2.7 - saving a 1D array and a 2D array on the same csvPython 2.7 - 在同一个 csv 上保存一维数组和二维数组
【发布时间】:2019-09-26 07:50:48
【问题描述】:

我有一个 sgape (4) 的一维数组,如下所示:

['rsmin_025_lai_chtessel' 
 'rsmin_050_lai_chtessel'
 'rsmin_075_lai_chtessel' 
 'rsmin_100_lai_chtessel']

和一个形状为 (4,12) 的二维数组如下:

[[ 8.  9. 20. 20. 19. 20. 20. 20. 20. 20. 20. 20.]
 [ 6.  8. 19. 17.  7. 19. 19. 19. 19. 19. 19. 19.]
 [ 4.  6. 18. 14.  3. 18. 15. 18. 18. 18. 18. 18.]
 [ 2.  4. 17. 11.  1. 17. 11. 14. 17. 17. 17. 17.]]

现在我想将这 2 个数组保存到 csv 中,为此我使用以下内容:

np.savetxt('jojo23.txt', (array1,array2))

返回以下错误:

ValueError: could not broadcast input array from shape (20,12) into shape (20)

有谁知道如何合并这两个数组以获得以下 csv 输出:

rsmin_025_lai_chtessel,8,9,20,20,19,20,20,20,20,20,20,20
rsmin_050_lai_chtessel,6,8,19,17,7,19,19,19,19,19,19,19
rsmin_075_lai_chtessel,4,6,18,14,3,18,15,18,18,18,18,18
rsmin_100_lai_chtessel,2,4,17,11,1,17,11,14,17,17,17,17

【问题讨论】:

  • 合并是什么意思?你检查过 numpy 中的任何连接函数吗?
  • 它试图将 (array1, array2) 变成一个新的数组。 savetxt 保存一个二维数组。

标签: python arrays csv numpy


【解决方案1】:

您可能希望对此类数据使用 JSON 格式。

否则,请尝试:

np.savetxt('jojo23.txt', np.c_[array1,array2])

np.c_[...] 是一种按列连接的快速方法。

【讨论】:

  • 它返回以下错误:TypeError: Mismatch between array dtype ('|S32') and format specifier ('%.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e')
  • 您的格式化程序 '%.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e %.18e' 用于浮点输入,所有内容都应转换为带有 np.c_[array1,array2] 的字符串类型数组,请尝试删除格式化程序。
  • 由于 arrat1 是字符串 np.c_ 产生一个字符串 dtype 数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 2018-09-20
  • 2017-12-13
相关资源
最近更新 更多