【问题标题】:How to write 2D numpy arrays into a file (readable; CSV form for excel upload later)?如何将 2D numpy 数组写入文件(可读;稍后上传 excel 的 CSV 表单)?
【发布时间】:2018-07-24 02:26:36
【问题描述】:

我有两个数组(大小为 6x3),想将内容写入文件。

pos_pb_now = np.array(pos_pb_now, dtype='f')
pos_pw_now = np.array(pos_pw_now, dtype='f')

np.savetxt(f_store_handler, pos_pb_now, fmt='%5.2f')

给了

  File "/usr/lib/python3/dist-packages/numpy/lib/npyio.py", line 1215, in savetxt
    fh.write(asbytes(format % tuple(row) + newline))
TypeError: write() argument must be str, not bytes

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/family/glade/game_uwr/game_uwr.py", line 871, in store_coord
    np.savetxt(f_store_handler, pos_pb_now, fmt='%5.2f')
  File "/usr/lib/python3/dist-packages/numpy/lib/npyio.py", line 1219, in savetxt
    % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('float32') and format specifier ('%5.2f %5.2f %5.2f')

有人知道如何解决这个问题吗?到目前为止,在 python 论坛中查看了几个解释都没有成功。

背景:这 6 人是一支球队的 6 名球员,在 3 个维度(空间)中移动。 2 个阵列代表 2 个团队(白色和蓝色)。通过将他们的运动存储到一个文件中(带有附加),我可以稍后调用他们的 3D 运动(在 excel 中模拟/计算)并进行匹配分析。有点像足球分析,但是是 3D 的。它将成为教练向初学者解释如何走正确位置并做出正确动作的工具。

形状 = (6, 3) 例子

[[ 0.83333331  1.          4.        ]
 [ 2.5         1.          4.        ]
 [ 4.16666651  1.          4.        ]
 [ 5.83333349  1.          4.        ]
 [ 7.5         1.          4.        ]
 [ 9.16666698  1.          4.        ]]

dtype = float32

【问题讨论】:

  • 它应该可以工作。 pos_pb_now.shape 和 `pos_pb_now.dtype' 是什么?一些示例行也可能有所帮助。
  • 我将 print(pos_pb_now.shape) print(pos_pb_now) print(pos_pb_now.dtype) 的输出添加到上一篇文章中
  • 从这里stackoverflow.com/questions/6081008/… import pandas as pd df = pd.DataFrame(pos_pb_now) df.to_csv(filename_coord_store, header=None, index=None) 这项工作。但我想避免使用熊猫。欢迎任何想法。

标签: arrays file numpy store


【解决方案1】:

如果您的数组如您所描述的那样,一个 (6,3) 浮点数,您的 savetxt 应该可以工作

In [162]: arr = np.arange(18.).reshape(6,3)
In [163]: arr
Out[163]: 
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.],
       [ 9., 10., 11.],
       [12., 13., 14.],
       [15., 16., 17.]])
In [164]: np.savetxt('test', arr, fmt='%5.2f')
In [165]: cat test
 0.00  1.00  2.00
 3.00  4.00  5.00
 6.00  7.00  8.00
 9.00 10.00 11.00
12.00 13.00 14.00
15.00 16.00 17.00

【讨论】:

  • 根据 stackoverflow 上的一篇文章,解决方案是打开文件,在 "w" 上添加一个 "b",现在它可以工作了。 f_store_handler = open(filename_coord_store, 'wb') 主题关闭。感谢大家的帮助和支持。
  • @floppy_molly,我没注意变量名f_store_handler。如果它是一个已经打开的文件,那么写入模式会有所不同。 savetxt 曾经需要一个“bw”文件。尽管它看起来像是最新版本,但 1.14 似乎可以很好地处理“w”模式。最初savetxt 试图在 Py3 中保持 Py2 字节串模式。
猜你喜欢
  • 2014-08-30
  • 2015-06-26
  • 2019-08-24
  • 2019-03-19
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
相关资源
最近更新 更多