473,909 Members | 4,177 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Numpy array to gzip file

I have a set of numpy arrays which I would like to save to a gzip
file. Here is an example without gzip:

b=numpy.ones(10 00000,dtype=num py.uint8)
a=numpy.zeros(1 000000,dtype=nu mpy.uint8)
fd = file('test.dat' ,'wb')
a.tofile(fd)
b.tofile(fd)
fd.close()

This works fine. However, this does not:

fd = gzip.open('test .dat','wb')
a.tofile(fd)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: first argument must be a string or open file

In the bigger picture, I want to be able to write multiple numpy
arrays with some metadata to a binary file for very fast reading, and
these arrays are pretty compressible (strings of small integers), so I
can probably benefit in speed and file size by gzipping.

Thanks,
Sean
Jun 27 '08 #1
3 5971
On Jun 11, 9:17 am, Sean Davis <seand...@gmail .comwrote:
I have a set of numpy arrays which I would like to save to a gzip
file. Here is an example without gzip:

b=numpy.ones(10 00000,dtype=num py.uint8)
a=numpy.zeros(1 000000,dtype=nu mpy.uint8)
fd = file('test.dat' ,'wb')
a.tofile(fd)
b.tofile(fd)
fd.close()

This works fine. However, this does not:

fd = gzip.open('test .dat','wb')
a.tofile(fd)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: first argument must be a string or open file

In the bigger picture, I want to be able to write multiple numpy
arrays with some metadata to a binary file for very fast reading, and
these arrays are pretty compressible (strings of small integers), so I
can probably benefit in speed and file size by gzipping.

Thanks,
Sean
Use
fd.write(a)

The documentation says that gzip simulates most of the methods of a
file object.
Apparently that means it does not subclass it. numpy.tofile wants a
file object
Or something like that.
Jun 27 '08 #2
On Jun 11, 12:42 pm, "drobi...@gmail .com" <drobi...@gmail .comwrote:
On Jun 11, 9:17 am, Sean Davis <seand...@gmail .comwrote:
I have a set of numpy arrays which I would like to save to a gzip
file. Here is an example without gzip:
b=numpy.ones(10 00000,dtype=num py.uint8)
a=numpy.zeros(1 000000,dtype=nu mpy.uint8)
fd = file('test.dat' ,'wb')
a.tofile(fd)
b.tofile(fd)
fd.close()
This works fine. However, this does not:
fd = gzip.open('test .dat','wb')
a.tofile(fd)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: first argument must be a string or open file
In the bigger picture, I want to be able to write multiple numpy
arrays with some metadata to a binary file for very fast reading, and
these arrays are pretty compressible (strings of small integers), so I
can probably benefit in speed and file size by gzipping.
Thanks,
Sean

Use
fd.write(a)
That seems to work fine. Just to add to the answer a bit, one can
then use:

b=numpy.frombuf fer(fd.read(),d type=numpy.uint 8)

to get the array back as a numpy uint8 array.

Thanks for the help.

Sean
Jun 27 '08 #3
Sean Davis wrote:
I have a set of numpy arrays which I would like to save to a gzip
file. Here is an example without gzip:

b=numpy.ones(10 00000,dtype=num py.uint8)
a=numpy.zeros(1 000000,dtype=nu mpy.uint8)
fd = file('test.dat' ,'wb')
a.tofile(fd)
b.tofile(fd)
fd.close()

This works fine. However, this does not:

fd = gzip.open('test .dat','wb')
a.tofile(fd)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: first argument must be a string or open file
As drobinow says, the .tofile() method needs an actual file object with a real
FILE* pointer underneath it. You will need to call fd.write() on strings (or
buffers) made from the arrays instead. If your arrays are large (as they must be
if compression helps), then you will probably want to split it up. Use
numpy.array_spl it() to do this. For example:

In [13]: import numpy

In [14]: a=numpy.zeros(1 000000,dtype=nu mpy.uint8)

In [15]: chunk_size = 256*1024

In [17]: import gzip

In [18]: fd = gzip.open('foo. gz', 'wb')

In [19]: for chunk in numpy.array_spl it(a, len(a) // chunk_size):
....: fd.write(buffer (chunk))
....:
In the bigger picture, I want to be able to write multiple numpy
arrays with some metadata to a binary file for very fast reading, and
these arrays are pretty compressible (strings of small integers), so I
can probably benefit in speed and file size by gzipping.
File size perhaps, but I suspect the speed gains you get will be swamped by the
Python-level manipulation you will have to do to reconstruct the array. You will
have to read in (partial!) strings and then put the data into an array. If you
think compression will really help, look into PyTables. It uses the HDF5 library
which includes the ability to compress arrays with gzip and other compression
schemes. All of the decompression happens in C, so you don't have to do all of
the manipulations at the Python level. If you stand to gain anything from
compression, this is the best way to find out and probably the best way to
implement it, too.

http://www.pytables.org

If you have more numpy questions, you will probably want to ask on the numpy
mailing list:

http://www.scipy.org/Mailing_Lists

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Jun 27 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1809
by: Andrew Felch | last post by:
So I wanted to matrixmultiply , ] * Of course this is impossible, because the number of columns in the
8
3876
by: Bo Peng | last post by:
Dear list, I am writing a Python extension module that needs a way to expose pieces of a big C array to python. Currently, I am using NumPy like the following: PyObject* res = PyArray_FromDimsAndData(1, int*dim, PyArray_DOUBLE, char*buf); Users will get a Numeric Array object and can change its values (and actually change the underlying C array).
2
3585
by: Justin Lemkul | last post by:
Hello all, I am hoping someone out there will be able to help me. I am trying to install a program that utilizes NumPy. In installing NumPy, I realized that I was lacking Atlas. I ran into the following problems installing Atlas and NumPy, as I realized that NumPy could be installed using the Mac OSX veclib already built in. If anyone has any ideas on how to fix either of these, I would be most grateful. I am fairly new to Python...
15
2201
by: nikie | last post by:
I'm a little bit stuck with NumPy here, and neither the docs nor trial&error seems to lead me anywhere: I've got a set of data points (x/y-coordinates) and want to fit a straight line through them, using LMSE linear regression. Simple enough. I thought instead of looking up the formulas I'd just see if there isn't a NumPy function that does exactly this. What I found was "linear_least_squares", but I can't figure out what kind of...
2
2802
by: robert | last post by:
in Gnuplot (Gnuplot.utils) the input array will be converted to a Numeric float array as shown below. When I insert a numpy array into Gnuplot like that below, numbers 7.44 are cast to 7.0 Why is this and what should I do ? Is this bug in numpy or in Numeric? >>m #numpy array array(, , , ..., ,
2
3978
by: Chris Smith | last post by:
Howdy, I'm a college student and for one of we are writing programs to numerically compute the parameters of antenna arrays. I decided to use Python to code up my programs. Up to now I haven't had a problem, however we have a problem set where we are creating a large matrix and finding it's inverse to solve the problem. To invert the matrix I've tried using numpy.numarray.linear_algebra.inverse and...
5
4139
by: auditory | last post by:
I am a newbie here I am trying to read "space separated floating point data" from file I read about csv module by searching this group, but I couldn't read space separated values with csv. (which may be matter of course..) I also read about numpy.fromfile(file, sep=' ') which i can use. but on my machine(ubuntu linux) numpy is unknown module,
7
1934
by: vj | last post by:
I've tried to post this to the numpy google group but it seems to be down. My migration seems to be going well. I currently have one issue with using scipy_base.insert. array() array() array(, dtype=int8) array() array()
3
2213
by: Duncan Smith | last post by:
Hello, Since moving to numpy I've had a few problems with my existing code. It basically revolves around the numpy scalar types. e.g. ------------------------------------------------ array(, ]) Traceback (most recent call last): File "<pyshell#30>", line 1, in -toplevel-
0
9877
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11346
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10538
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9725
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8097
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5938
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4774
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3357
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.