325 points · by calpaterson · 3y ago · 111 comments
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.
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.
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.
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.
If you use notebooks: my team is working on JupySQL, a tool to improve the SQL experience in Jupyter. https://github.com/ploomber/jupysql
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.
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...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
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.
Nah, you rightly are annoyed. When I am writing unit tests, it is especially annoying to fix the type.
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.)
In terms of that organization for persistent storage it certainly goes back to the earliest computers and even pre-computer punch card sorting systems.
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.)
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...)