r/Python • u/Psychological-Motor6 • Oct 06 '24
Showcase Python is awesome! Speed up Pandas point queries by 100x or even 1000x times.
Introducing NanoCube! I'm currently working on another Python library, called CubedPandas, that aims to make working with Pandas more convenient and fun, but it suffers from Pandas low performance when it comes to filtering data and executing aggregative point queries like the following:
value = df.loc[(df['make'].isin(['Audi', 'BMW']) & (df['engine'] == 'hybrid')]['revenue'].sum()So, can we do better? Yes, multi-dimensional OLAP-databases are a common solution. But, they're quite heavy and often not available for free. I needed something super lightweight, a minimal in-process in-memory OLAP engine that can convert a Pandas DataFrame into a multi-dimensional index for point queries only.
Thanks to the greatness of the Python language and ecosystem I ended up with less than 30 lines of (admittedly ugly) code that can speed up Pandas point queries by factor 10x, 100x or even 1,000x.
I wrapped it into a library called NanoCube, available through pip install nanocube. For source code, further details and some benchmarks please visit https://github.com/Zeutschler/nanocube.
from nanocube import NanoCube
nc = NanoCube(df)
value = nc.get('revenue', make=['Audi', 'BMW'], engine='hybrid')Target audience: NanoCube is useful for data engineers, analysts and scientists who want to speed up their data processing. Due to its low complexity, NanoCube is already suitable for production purposes.
If you find any issues or have further ideas, please let me know on here, or on Issues on Github.
27
u/idesireawill Oct 06 '24
Any comparisons with duckdb?
11
u/Fluffy-Diet-Engine Oct 06 '24
Kudos! Good work in making pandas faster.
I wanted to do a comparison between `polars.filter` and `NanoCube.get`. Curious about the performance gain. While writing code, I got stuck at writing a query like `.get(field > 123)`. I can see only `==` or ` = []` in documentation also. Can you help me here?
This is the polars query I am trying to replicate.
Data - https://www.kaggle.com/datasets/asmonline/spotify-song-performance-dataset
5
u/thegarthok Oct 06 '24
Would love to see an example! I think I understand in theory but my monkey brain won't ever think to use unless shown visually an example of when to use in a real life use case.
12
u/Obliterative_hippo Pythonista Oct 06 '24
Thank you for sharing! I may later incorporate this into the query_df() function of my library.
4
u/reallyserious Oct 06 '24
Just curious if you're aware of in-memory sqlite?
2
u/Psychological-Motor6 Oct 06 '24
Maybe one interesting addition, I have also written some first code for de-/serialization of a NanoCube.
NanoCube serializes and deserialises 4 -5x faster compared to Pandas using Arrow.
The size of a NanoCube file is up to 25% larger when source data was in random order. But when the source data has been sorted beforehand (columns with lower cardinality first and higher cardinality later), file size is up to 40% smaller than the respective DataFrame parquet file. For edge cases, e.g. when value columns are just 1s and 0s up to 90% smaller. I have a dataset with 7 columns, where just 1/2 a byte per record is required to store it. Reason for both achievements is again the magical RoaringBitmap library: http://roaringbitmap.org
Idea: Maybe it's a good idea to extend NanoCube to a full flavoured OLAP engine?!? Any opinions on that?
2
u/Psychological-Motor6 Oct 07 '24
Thanks to a request from u/reallyserious I added a simple result cache for recurring identical queries. By default the cache is on, but can be switched off
nc = NanoCube(df, caching=False).Caching adds less than 1% of query runtime, but yields even 100x times faster response times when accessing the same data multiple times. As the throughput for cached results gets close to 1M queries/sec (on my Mac), additional external caching is barely required. Enjoy...
You can find the Benchmark here:
https://github.com/Zeutschler/nanocube/blob/main/benchmarks/nano_vs_nano_cached.py
2
u/Psychological-Motor6 Oct 07 '24
Now it get's a little bit absurd...
After reading this research paper from the author of RoaringBitmaps, Daniel Lemire: https://arxiv.org/pdf/0901.3751 I decided to give it a spin and sort my DataFrames before converting them into NanoCubes. What to expect?
At the lower end of the spectrum (very random datasets) you can achieve only 10% of performance increase. But at the upper end it get's close to absurd. On a larger 10M row dataset with rather low cardinality in the dimension columns (2, 10, 100, 364, 1,000 and 10,000) sorting yields again factor 100x of performance increase. But please don't get too excited, the charts linked above are likely the very upper limit of potential performance improvements you can achieve by using NanoCube, not the average. Enjoy...
2
u/code_mc Oct 09 '24
I got inspired and started poking around with numpy sorted arrays as an alternative to the roaring bitmaps, I've opened a PR with my findings https://github.com/Zeutschler/nanocube/pull/19
1
u/Psychological-Motor6 Oct 10 '24
The repo has been moved to a separate GitHub Organisation: https://github.com/nanocubeai/nanocube
The org name "nanocubeai" was chosen because "nanocube" has already been taken. In addition it will have its own homepage nanocube.ai (.com, .org etc were already taken)
1
u/[deleted] Oct 07 '24
How does it stack against cudf? Looks like an awesome tool nonetheless
2
u/janek3d Oct 06 '24
Looks interesting
0
u/[deleted] Oct 06 '24
[deleted] — view deleted comment
-22
u/[deleted] Oct 06 '24
[removed] — view removed comment