I/O Kung-Fu: get your data in and out of Vaex

If you want to try out this notebook with a live Python kernel, use mybinder:

https://mybinder.org/badge_logo.svg

Data input

Every project starts with reading in some data. Vaex supports several data sources:

The following examples show the best practices of getting your data in Vaex.

Binary file formats

If your data is already in one of the supported binary file formats (HDF5, Apache Arrow, Apache Parquet, FITS), opening it with Vaex rather simple:

[1]:
import vaex

# Reading a HDF5 file
df_names = vaex.open('./data/io/sample_names_1.hdf5')
df_names
[1]:
# name agecity
0John 17Edinburgh
1Sally 33Groningen
[2]:
# Reading an arrow file
df_fruits = vaex.open('./data/io/sample_fruits.arrow')
df_fruits
[2]:
# fruit amountorigin
0mango 5Malaya
1banana 10Ecuador
2orange 7Spain

Opening such data is instantenous regardless of the file size on disk: Vaex will just memory-map the data instead of reading it in memory. This is the optimal way of working with large datasets that are larger than available RAM.

If your data is contained within multiple files, one can open them all simultaneously like this:

[3]:
df_names_all = vaex.open('./data/io/sample_names_*.hdf5')
df_names_all
[3]:
# name agecity
0John 17Edinburgh
1Sally 33Groningen
2Maria 23Caracas
3Monica 55New York

Alternatively, one can use the open_many method to pass a list of files to open:

[4]:
df_names_all = vaex.open_many(['./data/io/sample_names_1.hdf5',
                               './data/io/sample_names_2.hdf5'])
df_names_all
[4]:
# name agecity
0John 17Edinburgh
1Sally 33Groningen
2Maria 23Caracas
3Monica 55New York

The result will be a single DataFrame object containing all of the data coming from all files.

The data does not necessarily have to be local. With Vaex you can open a HDF5 file straight from Amazon’s S3:

[5]:
df_from_s3 = vaex.open('s3://vaex/testing/xys.hdf5?anon=true')
df_from_s3
[5]:
# x y s
0 1 3 5
1 2 4 6

In this case the data will be lazily downloaded and cached to the local machine. “Lazily downloaded” means that Vaex will only download the portions of the data you really need. For example: imagine that we have a file hosted on S3 that has 100 columns and 1 billion rows. Getting a preview of the DataFrame via print(df) for instance will download only the first and last 5 rows. If we than proceed to make calculations or plots with only 5 columns, only the data from those columns will be downloaded and cached to the local machine.

By default, data that is streamed from S3 is cached at $HOME/.vaex/file-cache/s3, and thus successive access is as fast as native disk access. One can also use the profile_name argument to use a specific S3 profile, which will than be passed to s3fs.core.S3FileSystem.

With Vaex one can also read-in parquet files:

[6]:
# Reading a parquet file
df_cars = vaex.open('./data/io/sample_cars.parquet')
df_cars
[6]:
# car color year
0renaultred 1996
1audi black 2005
2toyota blue 2000

Text based file formats

Datasets are still commonly stored in text-based file formats such as CSV. Since text-based file formats are not memory-mappable, they have to be read in memory. If the contents of a CSV file fits into the available RAM, one can simply do:

[7]:
df_nba = vaex.from_csv('./data/io/sample_nba_1.csv', copy_index=False)
df_nba
[7]:
# city team player
0IndianopolisPacers Reggie Miller
1Chicago Bulls Michael Jordan
2Boston CelticsLarry Bird

or alternatively:

[8]:
df_nba = vaex.read_csv('./data/io/sample_nba_1.csv', copy_index=False)
df_nba
[8]:
# city team player
0IndianopolisPacers Reggie Miller
1Chicago Bulls Michael Jordan
2Boston CelticsLarry Bird

Vaex is using pandas for reading CSV files in the background, so one can pass any arguments to the vaex.from_csv or vaex.read_csv as one would pass to pandas.read_csv and specify for example separators, column names and column types. The copy_index parameter specifies if the index column of the pandas DataFrame should be read as a regular column, or left out to save memory. In addition to this, if you specify the convert=True argument, the data will be automatically converted to an HDF5 file behind the scenes, thus freeing RAM and allowing you to work with your data in a memory-efficient, out-of-core manner.

If the CSV file is so large that it can not fit into RAM all at one time, one can convert the data to HDF5 simply by:

df = vaex.from_csv('./my_data/my_big_file.csv', convert=True, chunk_size=5_000_000)

When the above line is executed, Vaex will read the CSV in chunks, and convert each chunk to a temporary HDF5 file on disk. All temporary files are then concatenated into a single HDF5 file, and the temporary files deleted. The size of the individual chunks to be read can be specified via the chunk_size argument. Note that this automatic conversion requires free disk space of twice the final HDF5 file size.

It often happens that the data we need to analyse is spread over multiple CSV files. One can convert them to the HDF5 file format like this:

[9]:
list_of_files = ['./data/io/sample_nba_1.csv',
                 './data/io/sample_nba_2.csv',
                 './data/io/sample_nba_3.csv',]

# Convert each CSV file to HDF5
for file in list_of_files:
    df_tmp = vaex.from_csv(file, convert=True, copy_index=False)

The above code block converts in turn each CSV file to the HDF5 format. Note that the conversion will work regardless of the file size of each individual CSV file, provided there is sufficient storage space.

Working with all of the data is now easy: just open all of the relevant HDF5 files as described above:

[10]:
df = vaex.open('./data/io/sample_nba_*.csv.hdf5')
df
[10]:
# city team player
0IndianopolisPacers Reggie Miller
1Chicago Bulls Michael Jordan
2Boston CelticsLarry Bird
3Los Angeles Lakers Kobe Bryant
4Toronto RaptorsVince Carter
5Philadelphia76ers Allen Iverson
6San Antonio Spurs Tim Duncan

One can than additionally export this combined DataFrame to a single HDF5 file. This should lead to minor performance improvements.

[11]:
df.export('./data/io/sample_nba_combined.hdf5')

It is also common the data to be stored in JSON files. To read such data in Vaex one can do:

[12]:
df_isles = vaex.from_json('./data/io/sample_isles.json', orient='table', copy_index=False)
df_isles
[12]:
# isle size_sqkm
0Easter Island 163.6
1Fiji 18.333
2Tortuga 178.7

This is a convenience method which simply wraps pandas.read_json, so the same arguments and file reading strategy applies. If the data is distributed amongs multiple JSON files, one can apply a similar strategy as in the case of multiple CSV files: read each JSON file with the vaex.from_json method, convert it to a HDF5 or Arrow file format. Than use vaex.open or vaex.open_many methods to open all the converted files as a single DataFrame.

To learn more about different options of exporting data with Vaex, please read the next section below.

In-memory data representations

One can construct a Vaex DataFrame from a variety of in-memory data representations. Such a common operation is converting a pandas into a Vaex DataFrame. Let us read in a CSV file with pandas and than convert it to a Vaex DataFrame:

[13]:
import pandas as pd

pandas_df = pd.read_csv('./data/io/sample_nba_1.csv')
pandas_df
[13]:
city team player
0 Indianopolis Pacers Reggie Miller
1 Chicago Bulls Michael Jordan
2 Boston Celtics Larry Bird
[14]:
df = vaex.from_pandas(df=pandas_df, copy_index=True)
df
[14]:
# city team player index
0IndianopolisPacers Reggie Miller 0
1Chicago Bulls Michael Jordan 1
2Boston CelticsLarry Bird 2

The copy_index argument specifies whether the index column of a pandas DataFrame should be imported into the Vaex DataFrame. Converting a pandas into a Vaex DataFrame is particularly useful since pandas can read data from a large variety of file formats. For instance, we can use pandas to read data from a database, and then pass it to Vaex like so:

import vaex
import pandas as pd
import sqlalchemy

connection_string = 'postgresql://readonly:' + 'my_password' + '@server.company.com:1234/database_name'
engine = sqlalchemy.create_engine(connection_string)

pandas_df = pd.read_sql_query('SELECT * FROM MYTABLE', con=engine)
df = vaex.from_pandas(pandas_df, copy_index=False)

Another example is using pandas to read in SAS files:

[15]:
pandas_df = pd.read_sas('./data/io/sample_airline.sas7bdat')
df = vaex.from_pandas(pandas_df, copy_index=False)
df
[15]:
# YEAR Y W R L K
0 1948.01.21399998664855960.243000000715255740.1454000025987625 1.41499996185302730.6119999885559082
1 1949.01.35399997234344480.259999990463256840.218099996447563171.38399994373321530.5590000152587891
2 1950.01.569000005722046 0.277999997138977050.3156999945640564 1.38800001144409180.5730000138282776
3 1951.01.94799995422363280.296999990940094 0.393999993801116941.54999995231628420.5640000104904175
4 1952.02.265000104904175 0.3100000023841858 0.355899989604949951.80200004577636720.5740000009536743
... ... ... ... ... ... ...
271975.018.72100067138672 1.246999979019165 0.230100005865097055.72200012207031259.062000274658203
281976.019.25 1.375 0.3452000021934509 5.76200008392334 8.26200008392334
291977.020.64699935913086 1.5440000295639038 0.450800001621246345.876999855041504 7.473999977111816
301978.022.72599983215332 1.7029999494552612 0.5877000093460083 6.107999801635742 7.104000091552734
311979.023.6189994812011721.7790000438690186 0.534600019454956 6.85200023651123056.874000072479248

One can read in an arrow table as a Vaex DataFrame in a similar manner. Let us first use pyarrow to read in a CSV file as an arrow table.

[16]:
import pyarrow.csv

arrow_table = pyarrow.csv.read_csv('./data/io/sample_nba_1.csv')
arrow_table
[16]:
pyarrow.Table
city: string
team: string
player: string

Once we have the arrow table, converting it to a DataFrame is simple:

[17]:
df = vaex.from_arrow_table(arrow_table)
df
[17]:
# city team player
0IndianopolisPacers Reggie Miller
1Chicago Bulls Michael Jordan
2Boston CelticsLarry Bird

It also common to construct a Vaex DataFrame from numpy arrays. That can be done like this:

[18]:
import numpy as np

x = np.arange(2)
y = np.array([10, 20])
z = np.array(['dog', 'cat'])


df_numpy = vaex.from_arrays(x=x, y=y, z=z)
df_numpy
[18]:
# x yz
0 0 10dog
1 1 20cat

Constructing a DataFrame from a Python dict is also straight-forward:

[19]:
# Construct a DataFrame from Python dictionary
data_dict = dict(x=[2, 3], y=[30, 40], z=['cow', 'horse'])

df_dict = vaex.from_dict(data_dict)
df_dict
[19]:
# x yz
0 2 30cow
1 3 40horse

At times, one may need to create a single row DataFrame. Vaex has a convenience method which takes individual elements (scalars) and creates the DataFrame:

[20]:
df_single_row = vaex.from_scalars(x=4, y=50, z='mouse')
df_single_row
[20]:
# x yz
0 4 50mouse

Finally, we can choose to concatenate different DataFrames, without any memory penalties like so:

[21]:
df = vaex.concat([df_numpy, df_dict, df_single_row])
df
[21]:
# x yz
0 0 10dog
1 1 20cat
2 2 30cow
3 3 40horse
4 4 50mouse

Data export

One can export Vaex DataFrames to multiple file or in-memory data representations:

Binary file formats

The most efficient way to store data on disk when you work with Vaex is to use binary file formats. Vaex can export a DataFrame to HDF5, Apache Arrow, Apache Parquet and FITS:

[22]:
df.export_hdf5('./data/io/output_data.hdf5')
df.export_arrow('./data/io/output_data.arrow')
df.export_parquet('./data/io/output_data.parquet')

Alternatively, one can simply use:

[23]:
df.export('./data/io/output_data.hdf5')
df.export('./data/io/output_data.arrow')
df.export('./data/io/output_data.parquet')

where Vaex will determine the file format of the based on the specified extension of the file name. If the extension is not recognized, an exception will be raised.

If your data is large, i.e. larger than the available RAM, we recomment exporting to HDF5.

Text based file format

At times, it may be useful to export the data to disk in a text based file format such as CSV. In that case one can simply do:

[24]:
df.export_csv('./data/io/output_data.csv')  # `chunk_size` has a default value of 1_000_000

The df.export_csv method is using pandas_df.to_csv behind the scenes, and thus one can pass any argument to df.export_csv as would to pandas_df.to_csv. The data is exported in chunks and the size of those chunks can be specified by the chunk_size argument in df.export_csv. In this way, data that is too large to fit in RAM can be saved to disk.

In memory data representation

Python has a rich ecosystem comprised of various libraries for data manipulation, that offer different functionality. Thus, it is often useful to be able to pass data from one library to another. Vaex is able to pass on its data to other libraries via a number of in-memory representations.

DataFrame representations

A Vaex DataFrame can be converted to a pandas DataFrame like so:

[25]:
pandas_df = df.to_pandas_df()
pandas_df  # looks the same doesn't it?
[25]:
x y z
0 0 10 dog
1 1 20 cat
2 2 30 cow
3 3 40 horse
4 4 50 mouse

For DataFrames that are too large to fit in memory, one can specify the chunk_size argument, in which case the to_pandas_dfmethod returns a generator yileding a pandas DataFrame with as many rows as indicated by the chunk_size argument:

[26]:
gen = df.to_pandas_df(chunk_size=3)

for i1, i2, chunk in gen:
    print(i1, i2)
    print(chunk)
    print()
0 3
   x   y    z
0  0  10  dog
1  1  20  cat
2  2  30  cow

3 5
   x   y      z
0  3  40  horse
1  4  50  mouse

The generator also yields the row number of the first and the last element of that chunk, so we know exactly where in the parent DataFrame we are. The following DataFrame methods also support the chunk_size argument with the same behaviour.

Converting a Vaex DataFrame into an arrow table is similar:

[27]:
arrow_table = df.to_arrow_table()
arrow_table
[27]:
pyarrow.Table
x: int64
y: int64
z: string

One can simply convert the DataFrame to a list of arrays. By default, the data is exposed as a list of numpy arrays:

[28]:
arrays = df.to_arrays()
arrays
[28]:
[array([0, 1, 2, 3, 4]),
 array([10, 20, 30, 40, 50]),
 array(['dog', 'cat', 'cow', 'horse', 'mouse'], dtype=object)]

By specifying the array_type argument, one can choose whether the data will be represented by numpy arrays, xarrays, or Python lists.

[29]:
arrays = df.to_arrays(array_type='xarray')
arrays  # list of xarrays
[29]:
[<xarray.DataArray (dim_0: 5)>
 array([0, 1, 2, 3, 4])
 Dimensions without coordinates: dim_0, <xarray.DataArray (dim_0: 5)>
 array([10, 20, 30, 40, 50])
 Dimensions without coordinates: dim_0, <xarray.DataArray (dim_0: 5)>
 array(['dog', 'cat', 'cow', 'horse', 'mouse'], dtype=object)
 Dimensions without coordinates: dim_0]
[30]:
arrays = df.to_arrays(array_type='list')
arrays  # list of lists
[30]:
[[0, 1, 2, 3, 4],
 [10, 20, 30, 40, 50],
 ['dog', 'cat', 'cow', 'horse', 'mouse']]

Keeping it close to pure Python, one can export a Vaex DataFrame as a dictionary. The same array_type keyword argument applies here as well:

[31]:
d_dict = df.to_dict(array_type='numpy')
d_dict
[31]:
{'x': array([0, 1, 2, 3, 4]),
 'y': array([10, 20, 30, 40, 50]),
 'z': array(['dog', 'cat', 'cow', 'horse', 'mouse'], dtype=object)}

Alternatively, one can also convert a DataFrame to a list of tuples, were the first element of the tuple is the column name, while the second element is the array representation of the data.

[32]:
# Get a single item list
items = df.to_items(array_type='list')
items
[32]:
[('x', [0, 1, 2, 3, 4]),
 ('y', [10, 20, 30, 40, 50]),
 ('z', ['dog', 'cat', 'cow', 'horse', 'mouse'])]

As mentioned earlier, with all of the above example, one can use the chunk_size argument which creates a generator, yielding a portion of the DataFrame in the specified format. In the case of .to_dict method:

[33]:
gen = df.to_dict(array_type='list', chunk_size=2)

for i1, i2, chunk in gen:
    print(i1, i2, chunk)
0 2 {'x': [0, 1], 'y': [10, 20], 'z': ['dog', 'cat']}
2 4 {'x': [2, 3], 'y': [30, 40], 'z': ['cow', 'horse']}
4 5 {'x': [4], 'y': [50], 'z': ['mouse']}

Last but not least, a Vaex DataFrame can be lazily exposed as a Dask array:

[34]:
dask_arrays = df[['x', 'y']].to_dask_array()   # String support coming soon
dask_arrays
[34]:
Array Chunk
Bytes 80 B 80 B
Shape (5, 2) (5, 2)
Count 2 Tasks 1 Chunks
Type int64 numpy.ndarray
2 5

Expression representations

A single Vaex Expression can be also converted to a variety of in-memory representations:

[35]:
# pandas Series
x_series = df.x.to_pandas_series()
x_series
[35]:
0    0
1    1
2    2
3    3
4    4
dtype: int64
[36]:
# numpy array
x_numpy = df.x.to_numpy()
x_numpy
[36]:
array([0, 1, 2, 3, 4])
[37]:
# Python list
x_list = df.x.tolist()
x_list
[37]:
[0, 1, 2, 3, 4]
[38]:
# Dask array
x_dask_array = df.x.to_dask_array()
x_dask_array
[38]:
Array Chunk
Bytes 40 B 40 B
Shape (5,) (5,)
Count 2 Tasks 1 Chunks
Type int64 numpy.ndarray
5 1