Pandas 2.0
github.com
github.com
I keep Pandas around for quick plots and legacy code. I will always be grateful for Pandas because there truly was no good dataframe library during its time. It has enabled an entire generation of data scientists to do what they do and built a foundation — a foundation which Polars and DuckDB are now building on and have surpassed.
But yes, Polars and DuckDB can easily cast to Pandas and also read Pandas dataframes in memory. I have some legacy data transformations that are mostly DuckDB but involve some intermediate steps in Pandas (because I didn’t want to rewrite them) and it’s all seamless (though not zero copy as it would be in a pure Arrow workflow).
And ironically DuckDB can query Pandas dataframes faster than Pandas itself due to its vectorized engine.
I generally work with with Polars and DuckDB until the final step, when I cast it into a data structure I need (Pandas dataframe, Parquet etc)
All the expensive intermediate operations are taken care of in Polars and DuckDB.
Also a Polars dataframe — although it has different semantics — behaves like a Pandas dataframe for the most part. I haven’t had much trouble moving between it and Pandas.
There is a library called sklearn-pandas which doesn’t seem to be mainstream and dev has stopped since 2022.
> What should be the API for working with pandas, pyarrow, and dataclasses and/or pydantic?
> Pandas 2.0 supports pyarrow for so many things now, and pydantic does data validation with a drop-in dataclasses.dataclass replacement at pydantic.dataclasses.dataclass.
Model output may or may not converge given the enumeration ordering of Categorical CSVW columns, for example; so consistent round-trip (Linked Data) schema tool support would be essential.
CuML is scikit-learn API compatible and can use Dask for distributed and/or multi-GPU workloads. CuML is built on CuDF and CuPY; CuPy is a replacement for NumPy arrays on GPUs with 100x relative performance.
CuPy: https://github.com/cupy/cupy :
> CuPy is a NumPy/SciPy-compatible array library for GPU-accelerated computing with Python. CuPy acts as a drop-in replacement to run existing NumPy/SciPy code on NVIDIA CUDA or AMD ROCm platforms.
> CuPy is an open-source array library for GPU-accelerated computing with Python. CuPy utilizes CUDA Toolkit libraries including cuBLAS, cuRAND, cuSOLVER, cuSPARSE, cuFFT, cuDNN and NCCL to make full use of the GPU architecture.
> The figure shows CuPy speedup over NumPy. Most operations perform well on a GPU using CuPy out of the box. CuPy speeds up some operations more than 100X. Read the original benchmark article Single-GPU CuPy Speedups on the RAPIDS AI Medium blog
CuDF: https://github.com/rapidsai/cudf
CuML: https://github.com/rapidsai/cuml :
> cuML is a suite of libraries that implement machine learning algorithms and mathematical primitives functions that share compatible APIs with other RAPIDS projects.*
> cuML enables data scientists, researchers, and software engineers to run traditional tabular ML tasks on GPUs without going into the details of CUDA programming. In most cases, cuML's Python API matches the API from scikit-learn.
> For large datasets, these GPU-based implementations can complete 10-50x faster than their CPU equivalents. For details on performance, see the cuML Benchmarks Notebook.
FWICS there's now a ROCm version of CuPy, so it says CUDA (NVIDIA only) but also compiles for AMD. IDK whether there are plans to support Intel OneAPI, too.
What of the non-Arrow parts of other pandas-compatible and not pandas-compatible DataFrame libraries can be ported back to Pandas (and R)?
If you use notebooks: my team is working on JupySQL, a tool to improve the SQL experience in Jupyter. https://github.com/ploomber/jupysql
People have been trying to get rid of SQL for years yet they only end up reinventing it badly.
I’ve written a lot of code and the two notations I always gravitate toward are the magrittr + dplyr pipeline notation and SQL.
The chained methods notation is a bit too unergonomic especially to express window functions and complex joins.
Spark started out with method chaining but eventually found that most people used Spark SQL.
With columnar data DuckDuckGo is somuchfaster at this.
For one of my projects I have what sounds like a dumb workflow: - JSON api fetches get cached in sqlite3 - Parsing the JSON gets done with sqlite3 JSON operators (Fast! Fault tolerant! Handles NULLs nicely! Fast!!). - Collating data later gets queried with duckdb - everything gets munged and aggregated into the shape I want it and is persisted in parquet files - When it's time to consume it duckdb queries my various sources, does my (used to be expensive) groupbys onthefly and spits out pandas data frames - Lastly those data frames are small-ish, tidy and flexible
So yeah, on paper it sounds like these 3 libraries overlap too much to be use at the same time but in practice they can each have their place and interact well.
If you were to say “pandas in long format only” then yes that would be correct, but the power of pandas comes in its ability to work in a long relational or wide ndarray style. Pandas was originally written to replace excel in financial/econometric modeling, not as a replacement for sql. Models written solely in the long relational style are near unmaintainable for constantly evolving models with hundreds of data sources and thousands of interactions being developed and tuned by teams of analysts and engineers. For example, this is how some basic operations would look.
Bump prices in March 2023 up 10%:
# pandas
prices_df.loc['2023-03'] *= 1.1
# polars
polars_df.with_column(
pl.when(pl.col('timestamp').is_between(
datetime('2023-03-01'),
datetime('2023-03-31'),
include_bounds=True
)).then(pl.col('val') * 1.1)
.otherwise(pl.col('val'))
.alias('val')
)
Add expected temperature offsets to base temperature forecast at the state county level: # pandas
temp_df + offset_df
# polars
(
temp_df
.join(offset_df, on=['state', 'county', 'timestamp'], suffix='_r')
.with_column(
( pl.col('val') + pl.col('val_r')).alias('val')
)
.select(['state', 'county', 'timestamp', 'val'])
)
Now imagine thousands of such operations, and you can see the necessity of pandas in models like this.I typical do the type of column operation in your example only on subsets of data, and typically I do it in SQL using DuckDB. Interop between Polars and DuckDB is virtually zero cost so I seamlessly move between the two. And to be honest I don’t remember the last time I needed to do this but that’s just the nature of my work and not a generalized statement.
But yes if you are still in a world where you need to perform Excel like operations then I agree.
But you can move the explicitness of polars behind a function. A more explicit API should not hurt maintainability if we structure our code right.
def add(df1, df2, meta_cols, val_cols=None):
# join on meta cols
# add val cols (default to all non meta cols if None)
# return df with all meta and val cols selected
In theory I think that's fine. The problem is that in practice this will cause a lot of visual noise in your models, since for every operation you would need to specify, at least, your meta columns, and potentially value columns too. If you change the dimensionality of your data, you would need to update everywhere you've specified them. You could get around this a bit by defining the meta columns in a constant, but that's really only maintainable at a global module level. Once you start passing dfs around, you'll have to pass the specified columns as packaged data around with the df as well. There's also the problem that you'd need to use functions instead of standard operators.One thing that would be nice to do is set an (and forgive me, I understand the aversion to the word "index") index on the polars dataframe. Not a real index, just a list of columns that are specified as "metadata columns". This wouldn't actually affect any internal state of the data, but what it would do is affect the path of certain operations. Like if an "index" is set, then `+` does the join from above, rather than the current standard `+` operation.
In any case I realize this is a major philosophical divergence from the polars way of thinking, so more just shooting shit than offering real suggestions.
The SQL you're using finally in 2023 has enabled data scientists to do what they do for decades. Pandas was a massive derailment and distraction in what otherwise would have been called progress.
But for people who are looking for the performance polars gives with all the nice APIs of pandas, the big news is, since polars and pandas will now both use arrow for the underlying data, you can convert between the two kinds of dataframes without copying the data itself.
polars_df = polars.from_pandas(df)
# ... do performance heavy stuff ...
df = polars.to_pandas(polars_df)
There's a good article on it here:
https://datapythonista.me/blog/pandas-20-and-the-arrow-revol...Polars has Python API. It's much nicer than the Rust API. Plus the documentation is more complete.
So no, not a drop in replacement. But not a difficult transition either.
This page explains how Polars differs from Pandas.
https://pola-rs.github.io/polars-book/user-guide/coming_from...
df.with_columns( pl.when(pl.col("c") == 2) .then(pl.col("b")) .otherwise(pl.col("a")).alias("a") )
Seeing the multiple nested pl calls within a single expression just feels odd to me. It's definitely reminiscent of Dplyr but in a much less elegant way.
The method chaining syntax is unwieldy in any language.
Magrittr + dplyr (tidyverse) pipeline syntax is beautiful syntax but there’s a lot of magic with NSE (nonstandard evaluation) that makes it really tricky when you need to pass a variable column name.
I’ve sort of converged on SQL as the best compromise.
Looking at the Polars documentation also makes me nervous, due to how much of my current Pandas-fu relies on indexing to work. I appreciate that indexes can be NSE but it's how a lot of the current tools in my field work (python and in R) with important data in the index, eg, genes or cellular barcodes, and relying on the index to merge datasets.
Another caveat for me is at multiple times in my workflow I drop into R for plots and rpy2 can convert pandas dataframes into equivalent R atomics. With Polars it would be just an additional step of converting to pandas df but just something I need to consider. That said, I've disliked the Pandas syntax for so long that the mental overhead might be well worth it.
https://github.com/pola-rs/tpch/pull/36
Pandas having arrow as backend is great and will make interop with the arrow community (and polars) much better.
However, if you need performance, polars remains orders of magnitudes faster on whole queries, changing to the arrow memory format does not change that.
Would you happen to know if these two functions are faster in Polars?
.apply - might be faster in Polars but will not be as fast as using native expressions. That’s because applying a Python function invokes the GIL which kills parallelization and this is an inherent limitation of Python.
That said, I try not to use Python functions these days. I write transformations in SQL (or native expressions in Polars) and these can be executed at full speed with complete vectorization and parallelization.
Moving to SQL sounds like a good idea. I just don't have the time to convert my codebase and configure everything correctly.
https://modin.readthedocs.io/en/stable/getting_started/quick...
Kind of like "do I really need k8s?", "does my workload dictate I need SQL OLAP (Online Analytical Processing) / data frame lazy loading data library?"
what's the general rule of thumb to know "you're missing out by not using existing library like pandas/polars" for somebody who is out of the loop on this kind of stuff
That said, this is a 2023 comparison of Pandas and Polars memory usage.
Benchmarking that was shared a while back here suggests 2x speed ups in some cases, 30x if you count strings since pandas uses python's in-built string data type[1]
[1]https://datapythonista.me/blog/pandas-20-and-the-arrow-revol...
https://pola-rs.github.io/polars-book/user-guide/#current-st...
Polars’ lazy evaluation is a big deal — this lets it do query plan optimization.
Whereas in Pandas every step is eager so it can’t look ahead to eliminate redundant steps. You basically can’t do a lot of query optimization in a multi step transform.
[0]: https://pandas.pydata.org/pandas-docs/version/2.0/whatsnew/v...
> There is also an option to let pandas know we want Arrow backed types by default. The option at the time of writing this article is partially implemented and has a confusing API. In particular, it's not yet working when creating data with pandas.Series or pandas.DataFrame. And for loading data from files it will only work when the parameter use_nullable_dtypes is set to True. For example, to load a CSV file with PyArrow directly into PyArrow backed pandas Series, you can use the next code:
> pandas.options.mode.dtype_backend = 'pyarrow'
[1] https://datapythonista.me/blog/pandas-20-and-the-arrow-revol...
I'm excited to try out the new pyarrow dtypes, but it also sounds confusing that there are now 2 classes of types
Nah, you rightly are annoyed. When I am writing unit tests, it is especially annoying to fix the type.
I've implemented a function for schema based processing JSON documents for both vanilla python and pyspark that makes the process really easy. It'll take a schema and a document and product a list of flat dictionaries for python or a data frame for pyspark. Vanilla python is really streamable and keeps memory overhead low so it was actually faster than the pandas based workflows that it replaced.
Most of my notebooks are a mix of SQL and Python: SQL for most processing, dump the results as a pandas dataframe (via https://github.com/ploomber/jupysql) and then use Python for operations that are difficult to express with SQL (or that I don't know how to do it), so I end up with 80% SQL, 20% Python.
Unsure if this is the best workflow but it's the most efficient one I've come up with.
Disclaimer: my team develops JupySQL.
[1]: https://kartographie.geo.tu-dresden.de/ad/wip/ephemeral_even...
It is created by the folks who made Mondin (a scale out version of Pandas with API compatibility as a goal). Can use dask or ray as a backend.
Ponder is the enterprise version that runs on Snowflake and BigQuery. Again, same goal, API compatibility with Pandas. You can scale out your Pandas workflow by changing the import and leaving the Pandas code.
(Full disclosure I'm an advisor.)
Only big pain points are having to ship around boilerplate to construct SQLAlchemy create_engine URIs, and the performance limitations of SQLAlchemy’s inserts (if moving anything larger than a few gigs, it typically pays to ditch to_sql, and write a db-specific bulk insert process instead).
Is this going to mean I can’t do df[‘a’] = 2 to set all values in column a to 2?
https://www.tutorialspoint.com/python_pandas/python_pandas_p...
This isn't really true.
R took data frames from S, which was using the concept at least as early as 1991.
Pandas itself predates most if not all of the tidyverse. Pandas original release occurred in 2008, whereas the first release of dplyr (one of the original packages of the tidyverse), didn't come until 2014.
Was it?
(I have no idea. But R already had verbs operating on data frames.)
And, according to its author, Pandas took data frames from R - where data frames had been present from at least as early as 1997. (That part at least was true.)
In terms of that organization for persistent storage it certainly goes back to the earliest computers and even pre-computer punch card sorting systems.
Fast software only ever helps.
Can you give a citation from this, preferably from Wes himself?
Sadly this 2.0 release makes clear that Pandas is unlikely to evolve its API much further.
(I have just learned about PyStata, which is very interesting...)