[Numpy-discussion] tostring() for array rows

josef.pktd at gmail.com josef.pktd at gmail.com
Tue Oct 6 13:49:22 EDT 2009


If I have a structured or a regular array, is the use of strides in
the following always correct for the length of the row memory?

I would like to do tostring() but on each row, by creating a string
view of the memory in a 1d array.

Thanks,

Josef


>>> tmp = np.random.randn(4,3)
>>> tmp.ravel().view('S'+str(tmp.strides[0]))
array(['j\x94gv\xa5\x80\xe6?=\xea\xa3\xcb\xb9W\x05 at 4.\xa2J3\xe2\xee?',
       '\xe3\x89\x973My\xf7\xbf\xc1\x17\x0f\xff\xe9\x19\xb8\xbf\xdb?\x00\xc9c\xf0\xf9?',
       '\x1f\xc3,B\x9dQ\xa1?F\x1e\x12\x0f\x02\xfc\xd4\xbfz\xe0\xa5_G.\xd0?',
       '$#T\x0e\xad\x85\xfb\xbf\xf3S\xa6`\x89\x87\xdc?7]\xd9lt\xb4\xf4?'],
      dtype='|S24')

>>> tmp.tostring()
'j\x94gv\xa5\x80\xe6?=\xea\xa3\xcb\xb9W\x05 at 4.\xa2J3\xe2\xee?\xe3\x89\x973My\xf7\xbf\xc1\x17\x0f\xff\xe9\x19\xb8\xbf\xdb?\x00\xc9c\xf0\xf9?\x1f\xc3,B\x9dQ\xa1?F\x1e\x12\x0f\x02\xfc\xd4\xbfz\xe0\xa5_G.\xd0?$#T\x0e\xad\x85\xfb\xbf\xf3S\xa6`\x89\x87\xdc?7]\xd9lt\xb4\xf4?'

>>> tmp
array([(4.0, 0, 1), (1.0, 1, 3), (2.0, 2, 4), (4.0, 0, 1)],
      dtype=[('f0', '<f8'), ('f1', '<i4'), ('f2', '<i4')])
>>> tmp.view('S'+str(tmp.strides[0]))
array(['\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x01',
       '\x00\x00\x00\x00\x00\x00\xf0?\x01\x00\x00\x00\x03',
       '\x00\x00\x00\x00\x00\x00\x00@\x02\x00\x00\x00\x04',
       '\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x01'],
      dtype='|S16')



More information about the NumPy-Discussion mailing list