flicker


Nameflicker JSON
Version 1.0.1 PyPI version JSON
download
home_page
SummaryProvides FlickerDataFrame, a wrapper over Pyspark DataFrame to provide a pandas-like API
upload_time2023-10-20 04:29:40
maintainer
docs_urlNone
author
requires_python>=3.9
licenseApache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
keywords api dataframe pandas pyspark spark wrapper
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 🔥flicker
![GitHub](https://img.shields.io/github/license/ankur-gupta/flicker?link=https%3A%2F%2Fgithub.com%2Fankur-gupta%2Fflicker%2Fblob%2Fmain%2FLICENSE)
![build](https://img.shields.io/github/actions/workflow/status/ankur-gupta/flicker/build.yml)
[![codecov](https://codecov.io/gh/ankur-gupta/flicker/graph/badge.svg?token=iYwe8TbPrn)](https://codecov.io/gh/ankur-gupta/flicker)
![PyPI - Version](https://img.shields.io/pypi/v/flicker?link=https%3A%2F%2Fpypi.org%2Fproject%2Fflicker%2F)
![PyPI - Downloads](https://img.shields.io/pypi/dm/flicker)

<!-- TOC -->
* [🔥flicker](#flicker)
  * [What is `flicker`?](#what-is-flicker)
  * [How is `flicker` different than `pyspark.pandas` (formerly `koalas`)?](#how-is-flicker-different-than-pysparkpandas-formerly-koalas)
  * [Installation](#installation)
  * [Quick Example](#quick-example)
  * [Use the underlying PySpark DataFrame or Column](#use-the-underlying-pyspark-dataframe-or-column)
  * [Why not use `pyspark.pandas` (formerly `koalas`)?](#why-not-use-pysparkpandas-formerly-koalas)
  * [Status](#status)
  * [License](#license)
<!-- TOC -->

## What is `flicker`?
This python package provides a `FlickerDataFrame` object. `FlickerDataFrame`
is a thin wrapper over `pyspark.sql.DataFrame`. The aim of `FlickerDataFrame`
is to provide a more [Polars](https://www.pola.rs/)-like (not pandas-like) dataframe API. 
One way to understand `flicker`'s position is via the following analogy:

> _**keras** is to **tensorflow** as **flicker** is to **pyspark**_

`flicker` provides a modern, clean, intuitive, pythonic API over a `pyspark`
backend. `flicker` relies completely on `pyspark` for all distributed
computing work.

## How is `flicker` different than `pyspark.pandas` (formerly `koalas`)?
`flicker` is indeed just an alternative to `pyspark.pandas` (formerly `koalas`).
Theoretically, `pyspark.pandas` can provide similar functionality as `flicker` but, in practice,
`pyspark.pandas` suffers from severe performance and usability issues. You can see a detailed example 
[here](#why-not-use-pysparkpandas-formerly-koalas).

Flicker, on the other hand, is designed to provide a modern dataframe API. 
In terms for API design, Flicker is more similar to [Polars](https://www.pola.rs/) than to 
[Pandas](https://pandas.pydata.org/). Flicker is designed to be just as performant as PySpark itself.
And, finally, flicker considers interactive usage (such as exploratory data analysis) as the most important use case. 

## Installation
`flicker` is intended to be run with Python>=3.9 and PySpark>=3.4.1. We recommend Python 3.11 and PySpark 3.5.0.
You can install `flicker` from [PyPI](https://pypi.org/project/flicker/):
```bash
pip install flicker
```
If you need to set up Spark on your machine, see [pyspark-starter](https://github.com/ankur-gupta/pyspark-starter).

Alternatively, you can also build from source.
```bash
# Brief instructions. Modify to your requirements.
pip install hatch
git clone https://github.com/ankur-gupta/flicker 
cd $REPO_ROOT  # typically, ./flicker
hatch build 
pip install ./dist/flicker-1.0.0-py3-none-any.whl
```

## Quick Example
`flicker` aims to simplify some of the common and tedious aspects of a PySpark
dataframe without compromising performance. The following example shows some
of the features of `flicker`.

 ```python
from pyspark.sql import SparkSession
from flicker import FlickerDataFrame

# Get a spark session, if needed.
spark = SparkSession.builder.appName('PySparkShell').getOrCreate()

# Set case sensitivity to true.
# https://stackoverflow.com/a/62455158/4383754
spark.conf.set('spark.sql.caseSensitive', True)

# Flicker provides handy factory methods that you can use to create dataframes. 
# These factory methods are typically mostly useful to perform quick experiments.
# The easiest one is the `.from_shape` method.
df = FlickerDataFrame.from_shape(spark, nrows=100, ncols=3, names=['a', 'b', 'c'], fill='randn')

# Print the object to see the column names and types
# This returns immediately but doesn't print data.
df
# FlickerDataFrame[a: double, b: double, c: double]

# Best way to get started is to check the shape of the dataframe.
# Spark (and Flicker) already knows the number of columns but the number of rows needs to be
# computed, which can take some time.
df.shape
# (100, 3)

# You can also get the number of rows or columns directly.
df.nrows  # returns immediately because nrows is cached
# 100

df.ncols
# 3

# Instead of `df.columns`, use df.names for column names 
df.names
# ['a', 'b', 'c']

# dtypes is an OrderedDict
df.dtypes
# OrderedDict([('a', 'double'), ('b', 'double'), ('c', 'double')])

# You can get the dtype for a column name.
df.dtypes['b']
# 'double'

# One of the main features of flicker is the following handy shortcut to view the data.
# Calling a FlickerDataFrame object, returns the first 5 rows as a pandas DataFrame.
# See ?df for more examples on how you can use this to quickly and interactively perform analysis.
df()
#           a         b         c
# 0 -0.593432  0.768301 -0.302519
# 1  -0.11001  0.414888  0.075711
# 2 -0.997298  0.082082  1.080696
# 3  0.299431 -0.072324 -0.055095
# 4  -0.17833 -0.655759  0.252901

# Another cool feature of flicker is pandas-like assignment API. Instead of having to
# use .withColumn(), you can simply assign. For example, if we wanted to create a new
# column that indicates if df['a'] is positive or not, we can do it like this:
df['is_a_positive'] = df['a'] > 0

# See the new column 'is_a_positive'
df  # returns immediately
# FlickerDataFrame[a: double, b: double, c: double, is_a_positive: boolean]

# We can now 'call' df to view the first 5 rows.
df()
#           a         b         c is_a_positive
# 0 -0.593432  0.768301 -0.302519         False
# 1  -0.11001  0.414888  0.075711         False
# 2 -0.997298  0.082082  1.080696         False
# 3  0.299431 -0.072324 -0.055095          True
# 4  -0.17833 -0.655759  0.252901         False

# These features can intermixed in nearly every imaginable way. Here are some quick examples.
# Example 1: show the first 2 rows of the dataframe that has only 'a' and 'c' names selected.
df[['a', 'c']](2)
#           a         c
# 0 -0.593432 -0.302519
# 1  -0.11001  0.075711

# Example 2: Filter the data to select only the rows that have a positive value in column 'a' and
# show the first 3 rows of the filtered dataframe.
df[df['is_a_positive']](3)
#           a         b         c is_a_positive
# 0  0.299431 -0.072324 -0.055095          True
# 1  0.338228  -0.48378 -1.168131          True
# 2  0.578432 -1.223312 -0.546291          True

# Example 3: Show first 2 rows that have a positive product of 'a' and 'b'
df[(df['a'] * df['b']) > 0][['a', 'b']](2)
#           a         b
# 0  -0.17833 -0.655759
# 1 -0.054472  -0.82237

# You can also get some basic column operations done
df['a']  # returns immediately
# FlickerColumn<'a'>

# Show first 2 values of column 'a'
df[['a']](2)
#           a
# 0 -0.593432
# 1  -0.11001

# Describe the distribution of column 'a'
df[['a']].describe()
#                 a
# summary
# count         100
# mean    -0.024628
# stddev   0.980973
# min     -2.752549
# max      2.477625

# Get the value counts for 'is_a_positive' column 
df['is_a_positive'].value_counts()  # returns immediately
# FlickerDataFrame[is_a_positive: boolean, count: bigint]

# See the first 5 rows of the above dataframe by 'calling' it
df['is_a_positive'].value_counts()()
#   is_a_positive count
# 0         False    57
# 1          True    43

# Normalize the counts
df['is_a_positive'].value_counts(normalize=True)()
#   is_a_positive count
# 0         False  0.57
# 1          True  0.43
```

## Use the underlying PySpark DataFrame or Column
If `flicker` isn't enough, you can always use the underlying PySpark DataFrame.
Here are a few examples.
```python
from pyspark.sql import SparkSession
from flicker import FlickerDataFrame
from flicker.udf import type_udf

# Get a spark session, if needed.
spark = SparkSession.builder.appName('PySparkShell').getOrCreate()
spark.conf.set('spark.sql.caseSensitive', True)

# Create a more complicated dataframe using one of the factory methods
data = [(1, 'spark', 2.4, {}), (2, 'flicker', None, {'key': 1})]
column_names = ['a', 'b', 'c', 'd']
df = FlickerDataFrame.from_rows(spark, rows=data, names=column_names)
df
# FlickerDataFrame[a: bigint, b: string, c: double, d: map<string,bigint>]

# Typically, NaNs get converted into None(s) but be careful about None vs NaN issues. 
df()
#    a        b     c           d
# 0  1    spark   2.4          {}
# 1  2  flicker  None  {'key': 1}

# Always best to extract the FlickerDataFrame into pure python to verify if something is a NaN
# or None.
df.take()
# [{'a': 1, 'b': 'spark', 'c': 2.4, 'd': {}},
#  {'a': 2, 'b': 'flicker', 'c': None, 'd': {'key': 1}}]

# `._df` contains the underlying PySpark DataFrame.
# Note that `df._df` is immutable but `df` is mutable.
type(df._df)  # pyspark.sql.dataframe.DataFrame

# You can use call any of the underlying methods of `df._df`. Since, `df._df` is immutable,
# you don't have to worry about any `df._df.method()` call modifying `df`. 
df._df.show()
# +---+-------+----+----------+
# |  a|      b|   c|         d|
# +---+-------+----+----------+
# |  1|  spark| 2.4|        {}|
# |  2|flicker|NULL|{key -> 1}|
# +---+-------+----+----------+

# You can destructure a FlickerDataFrame by accessing the underlying columns
d = df['d']
d  # FlickerColumn<'d'>
type(d)  # flicker.column.FlickerColumn

# As before, you can access the underlying pyspark.sql.Column 
d._column  # Column<'d'>
type(d._column)  # pyspark.sql.column.Column

# You can call UDFs on the underlying pyspark.sql.Column
# For example, you can use the built-in flicker.udf.type_udf
df['d_type'] = type_udf(d._column)

# Note the new column 'd_type'
df
# FlickerDataFrame[a: bigint, b: string, c: double, d: map<string,bigint>, d_type: string]

# Use PySpark functions to compute the frequency table based on type of column 'd'
df._df.groupBy(['d_type']).count().show()
# +------+-----+
# |d_type|count|
# +------+-----+
# |  dict|    2|
# +------+-----+

# You can, of course, just use the value_counts method.
df['d_type'].value_counts()()
#   d_type count
# 0   dict     2

# You can always convert a PySpark DataFrame into a FlickerDataFrame
# after you've performed the native PySpark operations. This way, you can
# continue to enjoy the benefits of FlickerDataFrame. Converting a
# PySpark DataFrame into a FlickerDataFrame is always fast irrespective of
# dataframe size.
df_freq_table = FlickerDataFrame(df._df.groupBy(['d_type']).count())
df_freq_table()
#   d_type  count
# 0   dict      2
```

## Why not use `pyspark.pandas` (formerly `koalas`)?
[Koalas](https://koalas.readthedocs.io/en/latest/index.html) was a pandas API over Apache Spark, 
which was [officially included](https://issues.apache.org/jira/browse/SPARK-34849) in PySpark as 
[`pyspark.pandas`](https://spark.apache.org/docs/latest/api/python/migration_guide/koalas_to_pyspark.html).
Koalas is now deprecated and directs users towards `pyspark.pandas`.
You can see the documentation for `pyspark.pandas` [here](https://spark.apache.org/docs/latest/api/python/reference/pyspark.pandas/index.html).

While `pyspark.pandas` is the official, user-friendly dataframe API, there are three noticeable issues when working with 
it.
1. `pyspark.pandas` crashes with frequent `java.lang.OutOfMemoryError` errors even when `pyspark.sql.DataFrame` is 
capable of handling the same data size
2. `pyspark.pandas`'s design runs unnecessary spark queries even for non-data-dependent tasks (such as getting the 
documentation), making interactive use too cumbersome for real-life use 
3. `pyspark.pandas` inherits all the design choices, whether good or bad, from pandas

We demonstrate the above issues with a real-life example. You may need to set up your system for PySpark before 
you can run the example yourself; see [pyspark-starter](https://github.com/ankur-gupta/pyspark-starter).

For this example, we will use the publicly available 
[Speedtest by Ookla](https://registry.opendata.aws/speedtest-global-performance/) dataset on AWS S3.
This dataset has ~186M rows. The following code snippet was run on an Apple Macbook Pro (M2 Max, 32 GB).

```python
# pyspark.pandas.DataFrame: Frequent OOM errors
import pyspark.pandas as ps
pdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')
type(pdf)  # pyspark.pandas.frame.DataFrame
print(f'{pdf.shape[0] / 1e6: .1f}M')  # 185.8M

# Just getting one row fails
pdf.head(1)
# [Stage 5:=======>                           (9 + 12) / 70]
# java.lang.OutOfMemoryError: Java heap space
# ConnectionRefusedError: [Errno 61] Connection refused

# Python session is now unusable: we cannot run any other query now. 
pdf.head(1)  # fails immediately
# ConnectionRefusedError: [Errno 61] Connection refused

# We cannot even get the shape
pdf.shape  # fails immediately
# ConnectionRefusedError: [Errno 61] Connection refused

# We cannot reload the data either. Python session needs to be restarted. 
pdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')
# ConnectionRefusedError: [Errno 61] Connection refused
```

After encountering the OOM error, the entire python session is useless. We now need to restart the python session if 
we want to run more code. These OOM errors are too frequent and require frequent python restarts.   

While one might assume that this data is simply too big for our machine, that's not the case. 
We can easily load the same data as a Flicker (or `pyspark.sql.DataFrame`) dataframe, as shown below.

```python
# flicker.FlickerDataFrame or pyspark.sql.DataFrame: No OOM errors
# See https://github.com/ankur-gupta/pyspark-starter to set up your system for Pyspark and AWS S3. 
from pyspark.sql import SparkSession
from flicker import FlickerDataFrame
spark = SparkSession.builder.appName('PySparkShell').getOrCreate()

df = FlickerDataFrame(spark.read.parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet'))
print(f'{df.shape[0] / 1e6: .1f}M')  # 185.8M

type(df)  # flicker.dataframe.FlickerDataFrame
df()  # no OOM error
# [Stage 5:>                                    (0 + 1) / 1]
#             quadkey                                               tile avg_d_kbps avg_u_kbps avg_lat_ms tests devices
# 0  0022133222312322  POLYGON((-160.02685546875 70.6435894914449, -1...       8763       3646         45     1       1
# 1  0022133222330013  POLYGON((-160.032348632812 70.6399478155463, -...       9195       3347         43     1       1
# 2  0022133222330023  POLYGON((-160.043334960938 70.6363054807905, -...       6833       3788         42     1       1
# 3  0022133222330100  POLYGON((-160.02685546875 70.6417687358462, -1...       8895       3429         43     2       2
# 4  0022320121121332  POLYGON((-166.739501953125 68.3526207780586, -...       4877        935         45     3       2

df.shape  # returns immediately because nrows is cached
# (185832935, 7)
```

Let's give `pyspark.pandas.DataFrame` another shot. In a new python session, let's try some basic computation.
```python
# pyspark.pandas.DataFrame: Runs unnecessary spark queries
import pyspark.pandas as ps
pdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')

pdf.columns  # returns immediately
# Index(['quadkey', 'tile', 'avg_d_kbps', 'avg_u_kbps', 'avg_lat_ms', 'tests', 'devices'],
#        dtype='object')

# Just printing a column errors out. This is because pyspark.pandas tries to load too much 
# data at every operation. 
pdf['tests']  # OOM error
# [Stage 2:=======>                           (9 + 12) / 70]
# java.lang.OutOfMemoryError: Java heap space
# ConnectionRefusedError: [Errno 61] Connection refused

# As before, this python session is now useless. 
pdf['tests']
# ConnectionRefusedError: [Errno 61] Connection refused
```
As the above snippet shows, `pyspark.pandas` runs a spark query in order to mimic pandas-like behavior. 
This causes `pyspark.pandas` to load too much data at nearly every operation, which 
exacerbates the OOM error problem. Even if there is no OOM error, the repeated loading of too much data slows down 
everything, even when we don't actually want to perform a data-heavy computation. Here is an example.

```python
# In yet another new python session
# pyspark.pandas.DataFrame: Runs unnecessary spark queries
import pyspark.pandas as ps
pdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')

# Note that we didn't actually call the `.value_counts` method yet.
pdf['tests'].value_counts
# [Stage 2:=======>                           (9 + 12) / 70]
# java.lang.OutOfMemoryError: Java heap space
# ConnectionRefusedError: [Errno 61] Connection refused
```
We have to restart our python session yet again. This is what makes `pyspark.pandas` impractical for interactive use.
Interactive use is arguably the most important reason for the existence of a pandas-like API on Spark.

Sometimes, we are able to execute some operations before we eventually run out of memory.
```python
# In yet another new python session
import pyspark.pandas as ps
pdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')

type(pdf['tests'])  # pyspark.pandas.series.Series
pdf['tests'].value_counts()
# [Stage 2:=======>                           (9 + 12) / 71]
# 1       59630189
# 2       25653143
# 3       15311171
# 4       10511920
# 5        7820975
# 6        6146086
# 7        4972223
# ...
# 982          205
# 986          204
# Name: tests, dtype: int64
# Showing only the first 1000

pdf['tests'] == 0
# [Stage 5:===============>                  (19 + 12) / 70]
# java.lang.OutOfMemoryError: Java heap space
# ConnectionRefusedError: [Errno 61] Connection refused
```

The OOM error can happen even when the printable output is known to be small.
```python
# In yet another new python session
import pyspark.pandas as ps
pdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')

pdf['devices'].head(1)  # no OOM error
# 0    1
# Name: devices, dtype: int64

# Getting the documentation requires executes a spark query, which may or may not fail.
# Even without a failure, we must wait for the spark query to run just to see the documentation.
# This kills interactivity.
?pdf.apply
# [Stage 2:=======>                           (9 + 12) / 70]
# java.lang.OutOfMemoryError: Java heap space
# py4j.protocol.Py4JNetworkError: Error while sending or receiving

# Your machine may not see an error yet, but it'll still take a long time before you can see the documentation.
# Even if you encounter, you should still see the documentation after the long time.
# However, you'll now have to reload your python session.
pdf['devices'].head(1)
# ConnectionRefusedError: [Errno 61] Connection refused
```
`pyspark.pandas` is designed in a way that requires the execution of a spark query even if all you want to do is get
documentation of a method. This "feature" kills interactivity. You'll have to wait a long time for the query to execute
before you'll see the documentation. If the query finishes successfully, you'll just have had to wait a long time, which
can be annoying. If the query runs into an OOM error, you will still be able to see the documentation (after the long 
wait) but your python session will now need to be restarted.

Flicker and PySpark's original interface (`pyspark.sql.DataFrame`) does not suffer from these problems.
Obviously, both `flicker.FlickerDataFrame` and `pyspark.sql.DataFrame` can encounter OOM errors, but they don't suffer 
from design-induced OOM that are frequently with `pyspark.pandas`. 
Neither `pyspark.pandas` nor `pyspark.sql.DataFrame` run a spark query just to access documentation.

```python
# flicker.FlickerDataFrame or pyspark.sql.DataFrame: No spark query to access documentation
# See https://github.com/ankur-gupta/pyspark-starter to set up your system for Pyspark and AWS S3. 
from pyspark.sql import SparkSession
from flicker import FlickerDataFrame
spark = SparkSession.builder.appName('PySparkShell').getOrCreate()

df = FlickerDataFrame(spark.read.parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet'))
df  # returns immediately
# FlickerDataFrame[quadkey: string, tile: string, 
#                  avg_d_kbps: bigint, avg_u_kbps: bigint, avg_lat_ms: bigint, 
#                  tests: bigint, devices: bigint]

df.names
# ['quadkey', 'tile', 'avg_d_kbps', 'avg_u_kbps', 'avg_lat_ms', 'tests', 'devices']

df['tests']  # returns immediately
# FlickerColumn<'tests'>

df[['tests']]()  # no OOM error
#   tests
# 0     1
# 1     1
# 2     1
# 3     2
# 4     3

df['tests'].value_counts()  # returns immediately
# FlickerDataFrame[tests: bigint, count: bigint]

df['tests'].value_counts()()  # no OOM error
# [Stage 7:=======>                           (9 + 12) / 71]
#   tests     count
# 0     1  59630189
# 1     2  25653143
# 2     3  15311171
# 3     4  10511920
# 4     5   7820975

df['tests'] == 0  # returns immediately
# FlickerColumn<'(tests = 0)'>

(df['tests'] == 0).value_counts()  # returns immediately
# FlickerDataFrame[(tests = 0): boolean, count: bigint]

(df['tests'] == 0).value_counts()()  # no OOM error
# [Stage 14:=======>                          (9 + 12) / 71]
#   (tests = 0)      count
# 0       False  185832935

?df.head  # no spark query, no OOM error
# Signature: df.head(n: 'int | None' = 5) -> 'FlickerDataFrame'
# Docstring: <no docstring>
# File:      .../flicker/src/flicker/dataframe.py
# Type:      method

df[['devices']](1)  # no OOM error
#   devices
# 0       1

df[['devices']].value_counts()  # still no OOM error
# [Stage 11:=======>                         (10 + 12) / 71]
#   devices     count
# 0       1  92155855
# 1       2  30108598
# 2       3  15262519
# 3       4   9404369
# 4       5   6455647

# This is a more time-consuming query, but if the original `spark.sql.DataFrame` can run it,
# then so can `flicker.FlickerDataFrame`.
(df['quadkey'].astype('Long') % 5).value_counts()()
# [Stage 31:=======>                          (9 + 12) / 71]
#   (CAST(quadkey AS BIGINT) % 5)     count
# 0                             0  46468834
# 1                             2  46456313
# 2                             1  46454483
# 3                             3  46453305
# Weird! No 'quadkey' % 5 == 4. 
# We can keep going. No OOM error. No need to restart our python session.
```
We can keep going. There is always a chance that we will encounter an OOM for some operation. 
For example, we will get an expected OOM error if we tried to convert the entire ~186M-row `flicker.DataFrame` into 
a `pandas.DataFrame`. But, OOM errors are much less frequent than with `pyspark.pandas`. 
In our experiments, it is more likely that your AWS S3 token will expire before you encounter an OOM error. And, 
unlike, `pyspark.pandas`, `flicker` does not run unnecessary spark queries. This makes interactive use very efficient and predictable. 

## Status
`flicker` is actively being developed. While `flicker` is ready for use, please note that 
some API may be changed in the future. Also, it is very likely that you will need a function that has not yet 
written in `flicker`. In such cases, you can always use the underlying PySpark DataFrame to do
every operation that PySpark supports. Please consider filing an issue for
missing functions, bugs, or unintuitive API. Happy sparking!

## License
`flicker` is available under [Apache License 2.0](https://github.com/ankur-gupta/flicker/blob/master/LICENSE).

`flicker` depends on other python packages listed in [requirements.txt](https://github.com/ankur-gupta/flicker/blob/master/requirements.txt)
which have their own licenses. `flicker` releases do not bundle any code from
the dependencies directly.

The documentation is made using [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/)
theme which has [MIT License](https://squidfunk.github.io/mkdocs-material/license/).
            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "flicker",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": "",
    "keywords": "API,dataframe,pandas,pyspark,spark,wrapper",
    "author": "",
    "author_email": "Flicker Contributors <7110058+ankur-gupta@users.noreply.github.com>",
    "download_url": "https://files.pythonhosted.org/packages/29/ce/0896efb1685bc9d37bd9347fbed8ff3b5cf3d7a44abc7bc0bb0fca5f53b7/flicker-1.0.1.tar.gz",
    "platform": null,
    "description": "# \ud83d\udd25flicker\n![GitHub](https://img.shields.io/github/license/ankur-gupta/flicker?link=https%3A%2F%2Fgithub.com%2Fankur-gupta%2Fflicker%2Fblob%2Fmain%2FLICENSE)\n![build](https://img.shields.io/github/actions/workflow/status/ankur-gupta/flicker/build.yml)\n[![codecov](https://codecov.io/gh/ankur-gupta/flicker/graph/badge.svg?token=iYwe8TbPrn)](https://codecov.io/gh/ankur-gupta/flicker)\n![PyPI - Version](https://img.shields.io/pypi/v/flicker?link=https%3A%2F%2Fpypi.org%2Fproject%2Fflicker%2F)\n![PyPI - Downloads](https://img.shields.io/pypi/dm/flicker)\n\n<!-- TOC -->\n* [\ud83d\udd25flicker](#flicker)\n  * [What is `flicker`?](#what-is-flicker)\n  * [How is `flicker` different than `pyspark.pandas` (formerly `koalas`)?](#how-is-flicker-different-than-pysparkpandas-formerly-koalas)\n  * [Installation](#installation)\n  * [Quick Example](#quick-example)\n  * [Use the underlying PySpark DataFrame or Column](#use-the-underlying-pyspark-dataframe-or-column)\n  * [Why not use `pyspark.pandas` (formerly `koalas`)?](#why-not-use-pysparkpandas-formerly-koalas)\n  * [Status](#status)\n  * [License](#license)\n<!-- TOC -->\n\n## What is `flicker`?\nThis python package provides a `FlickerDataFrame` object. `FlickerDataFrame`\nis a thin wrapper over `pyspark.sql.DataFrame`. The aim of `FlickerDataFrame`\nis to provide a more [Polars](https://www.pola.rs/)-like (not pandas-like) dataframe API. \nOne way to understand `flicker`'s position is via the following analogy:\n\n> _**keras** is to **tensorflow** as **flicker** is to **pyspark**_\n\n`flicker` provides a modern, clean, intuitive, pythonic API over a `pyspark`\nbackend. `flicker` relies completely on `pyspark` for all distributed\ncomputing work.\n\n## How is `flicker` different than `pyspark.pandas` (formerly `koalas`)?\n`flicker` is indeed just an alternative to `pyspark.pandas` (formerly `koalas`).\nTheoretically, `pyspark.pandas` can provide similar functionality as `flicker` but, in practice,\n`pyspark.pandas` suffers from severe performance and usability issues. You can see a detailed example \n[here](#why-not-use-pysparkpandas-formerly-koalas).\n\nFlicker, on the other hand, is designed to provide a modern dataframe API. \nIn terms for API design, Flicker is more similar to [Polars](https://www.pola.rs/) than to \n[Pandas](https://pandas.pydata.org/). Flicker is designed to be just as performant as PySpark itself.\nAnd, finally, flicker considers interactive usage (such as exploratory data analysis) as the most important use case. \n\n## Installation\n`flicker` is intended to be run with Python>=3.9 and PySpark>=3.4.1. We recommend Python 3.11 and PySpark 3.5.0.\nYou can install `flicker` from [PyPI](https://pypi.org/project/flicker/):\n```bash\npip install flicker\n```\nIf you need to set up Spark on your machine, see [pyspark-starter](https://github.com/ankur-gupta/pyspark-starter).\n\nAlternatively, you can also build from source.\n```bash\n# Brief instructions. Modify to your requirements.\npip install hatch\ngit clone https://github.com/ankur-gupta/flicker \ncd $REPO_ROOT  # typically, ./flicker\nhatch build \npip install ./dist/flicker-1.0.0-py3-none-any.whl\n```\n\n## Quick Example\n`flicker` aims to simplify some of the common and tedious aspects of a PySpark\ndataframe without compromising performance. The following example shows some\nof the features of `flicker`.\n\n ```python\nfrom pyspark.sql import SparkSession\nfrom flicker import FlickerDataFrame\n\n# Get a spark session, if needed.\nspark = SparkSession.builder.appName('PySparkShell').getOrCreate()\n\n# Set case sensitivity to true.\n# https://stackoverflow.com/a/62455158/4383754\nspark.conf.set('spark.sql.caseSensitive', True)\n\n# Flicker provides handy factory methods that you can use to create dataframes. \n# These factory methods are typically mostly useful to perform quick experiments.\n# The easiest one is the `.from_shape` method.\ndf = FlickerDataFrame.from_shape(spark, nrows=100, ncols=3, names=['a', 'b', 'c'], fill='randn')\n\n# Print the object to see the column names and types\n# This returns immediately but doesn't print data.\ndf\n# FlickerDataFrame[a: double, b: double, c: double]\n\n# Best way to get started is to check the shape of the dataframe.\n# Spark (and Flicker) already knows the number of columns but the number of rows needs to be\n# computed, which can take some time.\ndf.shape\n# (100, 3)\n\n# You can also get the number of rows or columns directly.\ndf.nrows  # returns immediately because nrows is cached\n# 100\n\ndf.ncols\n# 3\n\n# Instead of `df.columns`, use df.names for column names \ndf.names\n# ['a', 'b', 'c']\n\n# dtypes is an OrderedDict\ndf.dtypes\n# OrderedDict([('a', 'double'), ('b', 'double'), ('c', 'double')])\n\n# You can get the dtype for a column name.\ndf.dtypes['b']\n# 'double'\n\n# One of the main features of flicker is the following handy shortcut to view the data.\n# Calling a FlickerDataFrame object, returns the first 5 rows as a pandas DataFrame.\n# See ?df for more examples on how you can use this to quickly and interactively perform analysis.\ndf()\n#           a         b         c\n# 0 -0.593432  0.768301 -0.302519\n# 1  -0.11001  0.414888  0.075711\n# 2 -0.997298  0.082082  1.080696\n# 3  0.299431 -0.072324 -0.055095\n# 4  -0.17833 -0.655759  0.252901\n\n# Another cool feature of flicker is pandas-like assignment API. Instead of having to\n# use .withColumn(), you can simply assign. For example, if we wanted to create a new\n# column that indicates if df['a'] is positive or not, we can do it like this:\ndf['is_a_positive'] = df['a'] > 0\n\n# See the new column 'is_a_positive'\ndf  # returns immediately\n# FlickerDataFrame[a: double, b: double, c: double, is_a_positive: boolean]\n\n# We can now 'call' df to view the first 5 rows.\ndf()\n#           a         b         c is_a_positive\n# 0 -0.593432  0.768301 -0.302519         False\n# 1  -0.11001  0.414888  0.075711         False\n# 2 -0.997298  0.082082  1.080696         False\n# 3  0.299431 -0.072324 -0.055095          True\n# 4  -0.17833 -0.655759  0.252901         False\n\n# These features can intermixed in nearly every imaginable way. Here are some quick examples.\n# Example 1: show the first 2 rows of the dataframe that has only 'a' and 'c' names selected.\ndf[['a', 'c']](2)\n#           a         c\n# 0 -0.593432 -0.302519\n# 1  -0.11001  0.075711\n\n# Example 2: Filter the data to select only the rows that have a positive value in column 'a' and\n# show the first 3 rows of the filtered dataframe.\ndf[df['is_a_positive']](3)\n#           a         b         c is_a_positive\n# 0  0.299431 -0.072324 -0.055095          True\n# 1  0.338228  -0.48378 -1.168131          True\n# 2  0.578432 -1.223312 -0.546291          True\n\n# Example 3: Show first 2 rows that have a positive product of 'a' and 'b'\ndf[(df['a'] * df['b']) > 0][['a', 'b']](2)\n#           a         b\n# 0  -0.17833 -0.655759\n# 1 -0.054472  -0.82237\n\n# You can also get some basic column operations done\ndf['a']  # returns immediately\n# FlickerColumn<'a'>\n\n# Show first 2 values of column 'a'\ndf[['a']](2)\n#           a\n# 0 -0.593432\n# 1  -0.11001\n\n# Describe the distribution of column 'a'\ndf[['a']].describe()\n#                 a\n# summary\n# count         100\n# mean    -0.024628\n# stddev   0.980973\n# min     -2.752549\n# max      2.477625\n\n# Get the value counts for 'is_a_positive' column \ndf['is_a_positive'].value_counts()  # returns immediately\n# FlickerDataFrame[is_a_positive: boolean, count: bigint]\n\n# See the first 5 rows of the above dataframe by 'calling' it\ndf['is_a_positive'].value_counts()()\n#   is_a_positive count\n# 0         False    57\n# 1          True    43\n\n# Normalize the counts\ndf['is_a_positive'].value_counts(normalize=True)()\n#   is_a_positive count\n# 0         False  0.57\n# 1          True  0.43\n```\n\n## Use the underlying PySpark DataFrame or Column\nIf `flicker` isn't enough, you can always use the underlying PySpark DataFrame.\nHere are a few examples.\n```python\nfrom pyspark.sql import SparkSession\nfrom flicker import FlickerDataFrame\nfrom flicker.udf import type_udf\n\n# Get a spark session, if needed.\nspark = SparkSession.builder.appName('PySparkShell').getOrCreate()\nspark.conf.set('spark.sql.caseSensitive', True)\n\n# Create a more complicated dataframe using one of the factory methods\ndata = [(1, 'spark', 2.4, {}), (2, 'flicker', None, {'key': 1})]\ncolumn_names = ['a', 'b', 'c', 'd']\ndf = FlickerDataFrame.from_rows(spark, rows=data, names=column_names)\ndf\n# FlickerDataFrame[a: bigint, b: string, c: double, d: map<string,bigint>]\n\n# Typically, NaNs get converted into None(s) but be careful about None vs NaN issues. \ndf()\n#    a        b     c           d\n# 0  1    spark   2.4          {}\n# 1  2  flicker  None  {'key': 1}\n\n# Always best to extract the FlickerDataFrame into pure python to verify if something is a NaN\n# or None.\ndf.take()\n# [{'a': 1, 'b': 'spark', 'c': 2.4, 'd': {}},\n#  {'a': 2, 'b': 'flicker', 'c': None, 'd': {'key': 1}}]\n\n# `._df` contains the underlying PySpark DataFrame.\n# Note that `df._df` is immutable but `df` is mutable.\ntype(df._df)  # pyspark.sql.dataframe.DataFrame\n\n# You can use call any of the underlying methods of `df._df`. Since, `df._df` is immutable,\n# you don't have to worry about any `df._df.method()` call modifying `df`. \ndf._df.show()\n# +---+-------+----+----------+\n# |  a|      b|   c|         d|\n# +---+-------+----+----------+\n# |  1|  spark| 2.4|        {}|\n# |  2|flicker|NULL|{key -> 1}|\n# +---+-------+----+----------+\n\n# You can destructure a FlickerDataFrame by accessing the underlying columns\nd = df['d']\nd  # FlickerColumn<'d'>\ntype(d)  # flicker.column.FlickerColumn\n\n# As before, you can access the underlying pyspark.sql.Column \nd._column  # Column<'d'>\ntype(d._column)  # pyspark.sql.column.Column\n\n# You can call UDFs on the underlying pyspark.sql.Column\n# For example, you can use the built-in flicker.udf.type_udf\ndf['d_type'] = type_udf(d._column)\n\n# Note the new column 'd_type'\ndf\n# FlickerDataFrame[a: bigint, b: string, c: double, d: map<string,bigint>, d_type: string]\n\n# Use PySpark functions to compute the frequency table based on type of column 'd'\ndf._df.groupBy(['d_type']).count().show()\n# +------+-----+\n# |d_type|count|\n# +------+-----+\n# |  dict|    2|\n# +------+-----+\n\n# You can, of course, just use the value_counts method.\ndf['d_type'].value_counts()()\n#   d_type count\n# 0   dict     2\n\n# You can always convert a PySpark DataFrame into a FlickerDataFrame\n# after you've performed the native PySpark operations. This way, you can\n# continue to enjoy the benefits of FlickerDataFrame. Converting a\n# PySpark DataFrame into a FlickerDataFrame is always fast irrespective of\n# dataframe size.\ndf_freq_table = FlickerDataFrame(df._df.groupBy(['d_type']).count())\ndf_freq_table()\n#   d_type  count\n# 0   dict      2\n```\n\n## Why not use `pyspark.pandas` (formerly `koalas`)?\n[Koalas](https://koalas.readthedocs.io/en/latest/index.html) was a pandas API over Apache Spark, \nwhich was [officially included](https://issues.apache.org/jira/browse/SPARK-34849) in PySpark as \n[`pyspark.pandas`](https://spark.apache.org/docs/latest/api/python/migration_guide/koalas_to_pyspark.html).\nKoalas is now deprecated and directs users towards `pyspark.pandas`.\nYou can see the documentation for `pyspark.pandas` [here](https://spark.apache.org/docs/latest/api/python/reference/pyspark.pandas/index.html).\n\nWhile `pyspark.pandas` is the official, user-friendly dataframe API, there are three noticeable issues when working with \nit.\n1. `pyspark.pandas` crashes with frequent `java.lang.OutOfMemoryError` errors even when `pyspark.sql.DataFrame` is \ncapable of handling the same data size\n2. `pyspark.pandas`'s design runs unnecessary spark queries even for non-data-dependent tasks (such as getting the \ndocumentation), making interactive use too cumbersome for real-life use \n3. `pyspark.pandas` inherits all the design choices, whether good or bad, from pandas\n\nWe demonstrate the above issues with a real-life example. You may need to set up your system for PySpark before \nyou can run the example yourself; see [pyspark-starter](https://github.com/ankur-gupta/pyspark-starter).\n\nFor this example, we will use the publicly available \n[Speedtest by Ookla](https://registry.opendata.aws/speedtest-global-performance/) dataset on AWS S3.\nThis dataset has ~186M rows. The following code snippet was run on an Apple Macbook Pro (M2 Max, 32 GB).\n\n```python\n# pyspark.pandas.DataFrame: Frequent OOM errors\nimport pyspark.pandas as ps\npdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')\ntype(pdf)  # pyspark.pandas.frame.DataFrame\nprint(f'{pdf.shape[0] / 1e6: .1f}M')  # 185.8M\n\n# Just getting one row fails\npdf.head(1)\n# [Stage 5:=======>                           (9 + 12) / 70]\n# java.lang.OutOfMemoryError: Java heap space\n# ConnectionRefusedError: [Errno 61] Connection refused\n\n# Python session is now unusable: we cannot run any other query now. \npdf.head(1)  # fails immediately\n# ConnectionRefusedError: [Errno 61] Connection refused\n\n# We cannot even get the shape\npdf.shape  # fails immediately\n# ConnectionRefusedError: [Errno 61] Connection refused\n\n# We cannot reload the data either. Python session needs to be restarted. \npdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')\n# ConnectionRefusedError: [Errno 61] Connection refused\n```\n\nAfter encountering the OOM error, the entire python session is useless. We now need to restart the python session if \nwe want to run more code. These OOM errors are too frequent and require frequent python restarts.   \n\nWhile one might assume that this data is simply too big for our machine, that's not the case. \nWe can easily load the same data as a Flicker (or `pyspark.sql.DataFrame`) dataframe, as shown below.\n\n```python\n# flicker.FlickerDataFrame or pyspark.sql.DataFrame: No OOM errors\n# See https://github.com/ankur-gupta/pyspark-starter to set up your system for Pyspark and AWS S3. \nfrom pyspark.sql import SparkSession\nfrom flicker import FlickerDataFrame\nspark = SparkSession.builder.appName('PySparkShell').getOrCreate()\n\ndf = FlickerDataFrame(spark.read.parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet'))\nprint(f'{df.shape[0] / 1e6: .1f}M')  # 185.8M\n\ntype(df)  # flicker.dataframe.FlickerDataFrame\ndf()  # no OOM error\n# [Stage 5:>                                    (0 + 1) / 1]\n#             quadkey                                               tile avg_d_kbps avg_u_kbps avg_lat_ms tests devices\n# 0  0022133222312322  POLYGON((-160.02685546875 70.6435894914449, -1...       8763       3646         45     1       1\n# 1  0022133222330013  POLYGON((-160.032348632812 70.6399478155463, -...       9195       3347         43     1       1\n# 2  0022133222330023  POLYGON((-160.043334960938 70.6363054807905, -...       6833       3788         42     1       1\n# 3  0022133222330100  POLYGON((-160.02685546875 70.6417687358462, -1...       8895       3429         43     2       2\n# 4  0022320121121332  POLYGON((-166.739501953125 68.3526207780586, -...       4877        935         45     3       2\n\ndf.shape  # returns immediately because nrows is cached\n# (185832935, 7)\n```\n\nLet's give `pyspark.pandas.DataFrame` another shot. In a new python session, let's try some basic computation.\n```python\n# pyspark.pandas.DataFrame: Runs unnecessary spark queries\nimport pyspark.pandas as ps\npdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')\n\npdf.columns  # returns immediately\n# Index(['quadkey', 'tile', 'avg_d_kbps', 'avg_u_kbps', 'avg_lat_ms', 'tests', 'devices'],\n#        dtype='object')\n\n# Just printing a column errors out. This is because pyspark.pandas tries to load too much \n# data at every operation. \npdf['tests']  # OOM error\n# [Stage 2:=======>                           (9 + 12) / 70]\n# java.lang.OutOfMemoryError: Java heap space\n# ConnectionRefusedError: [Errno 61] Connection refused\n\n# As before, this python session is now useless. \npdf['tests']\n# ConnectionRefusedError: [Errno 61] Connection refused\n```\nAs the above snippet shows, `pyspark.pandas` runs a spark query in order to mimic pandas-like behavior. \nThis causes `pyspark.pandas` to load too much data at nearly every operation, which \nexacerbates the OOM error problem. Even if there is no OOM error, the repeated loading of too much data slows down \neverything, even when we don't actually want to perform a data-heavy computation. Here is an example.\n\n```python\n# In yet another new python session\n# pyspark.pandas.DataFrame: Runs unnecessary spark queries\nimport pyspark.pandas as ps\npdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')\n\n# Note that we didn't actually call the `.value_counts` method yet.\npdf['tests'].value_counts\n# [Stage 2:=======>                           (9 + 12) / 70]\n# java.lang.OutOfMemoryError: Java heap space\n# ConnectionRefusedError: [Errno 61] Connection refused\n```\nWe have to restart our python session yet again. This is what makes `pyspark.pandas` impractical for interactive use.\nInteractive use is arguably the most important reason for the existence of a pandas-like API on Spark.\n\nSometimes, we are able to execute some operations before we eventually run out of memory.\n```python\n# In yet another new python session\nimport pyspark.pandas as ps\npdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')\n\ntype(pdf['tests'])  # pyspark.pandas.series.Series\npdf['tests'].value_counts()\n# [Stage 2:=======>                           (9 + 12) / 71]\n# 1       59630189\n# 2       25653143\n# 3       15311171\n# 4       10511920\n# 5        7820975\n# 6        6146086\n# 7        4972223\n# ...\n# 982          205\n# 986          204\n# Name: tests, dtype: int64\n# Showing only the first 1000\n\npdf['tests'] == 0\n# [Stage 5:===============>                  (19 + 12) / 70]\n# java.lang.OutOfMemoryError: Java heap space\n# ConnectionRefusedError: [Errno 61] Connection refused\n```\n\nThe OOM error can happen even when the printable output is known to be small.\n```python\n# In yet another new python session\nimport pyspark.pandas as ps\npdf = ps.read_parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet')\n\npdf['devices'].head(1)  # no OOM error\n# 0    1\n# Name: devices, dtype: int64\n\n# Getting the documentation requires executes a spark query, which may or may not fail.\n# Even without a failure, we must wait for the spark query to run just to see the documentation.\n# This kills interactivity.\n?pdf.apply\n# [Stage 2:=======>                           (9 + 12) / 70]\n# java.lang.OutOfMemoryError: Java heap space\n# py4j.protocol.Py4JNetworkError: Error while sending or receiving\n\n# Your machine may not see an error yet, but it'll still take a long time before you can see the documentation.\n# Even if you encounter, you should still see the documentation after the long time.\n# However, you'll now have to reload your python session.\npdf['devices'].head(1)\n# ConnectionRefusedError: [Errno 61] Connection refused\n```\n`pyspark.pandas` is designed in a way that requires the execution of a spark query even if all you want to do is get\ndocumentation of a method. This \"feature\" kills interactivity. You'll have to wait a long time for the query to execute\nbefore you'll see the documentation. If the query finishes successfully, you'll just have had to wait a long time, which\ncan be annoying. If the query runs into an OOM error, you will still be able to see the documentation (after the long \nwait) but your python session will now need to be restarted.\n\nFlicker and PySpark's original interface (`pyspark.sql.DataFrame`) does not suffer from these problems.\nObviously, both `flicker.FlickerDataFrame` and `pyspark.sql.DataFrame` can encounter OOM errors, but they don't suffer \nfrom design-induced OOM that are frequently with `pyspark.pandas`. \nNeither `pyspark.pandas` nor `pyspark.sql.DataFrame` run a spark query just to access documentation.\n\n```python\n# flicker.FlickerDataFrame or pyspark.sql.DataFrame: No spark query to access documentation\n# See https://github.com/ankur-gupta/pyspark-starter to set up your system for Pyspark and AWS S3. \nfrom pyspark.sql import SparkSession\nfrom flicker import FlickerDataFrame\nspark = SparkSession.builder.appName('PySparkShell').getOrCreate()\n\ndf = FlickerDataFrame(spark.read.parquet('s3a://ookla-open-data/parquet/performance/type=*/year=*/quarter=*/*.parquet'))\ndf  # returns immediately\n# FlickerDataFrame[quadkey: string, tile: string, \n#                  avg_d_kbps: bigint, avg_u_kbps: bigint, avg_lat_ms: bigint, \n#                  tests: bigint, devices: bigint]\n\ndf.names\n# ['quadkey', 'tile', 'avg_d_kbps', 'avg_u_kbps', 'avg_lat_ms', 'tests', 'devices']\n\ndf['tests']  # returns immediately\n# FlickerColumn<'tests'>\n\ndf[['tests']]()  # no OOM error\n#   tests\n# 0     1\n# 1     1\n# 2     1\n# 3     2\n# 4     3\n\ndf['tests'].value_counts()  # returns immediately\n# FlickerDataFrame[tests: bigint, count: bigint]\n\ndf['tests'].value_counts()()  # no OOM error\n# [Stage 7:=======>                           (9 + 12) / 71]\n#   tests     count\n# 0     1  59630189\n# 1     2  25653143\n# 2     3  15311171\n# 3     4  10511920\n# 4     5   7820975\n\ndf['tests'] == 0  # returns immediately\n# FlickerColumn<'(tests = 0)'>\n\n(df['tests'] == 0).value_counts()  # returns immediately\n# FlickerDataFrame[(tests = 0): boolean, count: bigint]\n\n(df['tests'] == 0).value_counts()()  # no OOM error\n# [Stage 14:=======>                          (9 + 12) / 71]\n#   (tests = 0)      count\n# 0       False  185832935\n\n?df.head  # no spark query, no OOM error\n# Signature: df.head(n: 'int | None' = 5) -> 'FlickerDataFrame'\n# Docstring: <no docstring>\n# File:      .../flicker/src/flicker/dataframe.py\n# Type:      method\n\ndf[['devices']](1)  # no OOM error\n#   devices\n# 0       1\n\ndf[['devices']].value_counts()  # still no OOM error\n# [Stage 11:=======>                         (10 + 12) / 71]\n#   devices     count\n# 0       1  92155855\n# 1       2  30108598\n# 2       3  15262519\n# 3       4   9404369\n# 4       5   6455647\n\n# This is a more time-consuming query, but if the original `spark.sql.DataFrame` can run it,\n# then so can `flicker.FlickerDataFrame`.\n(df['quadkey'].astype('Long') % 5).value_counts()()\n# [Stage 31:=======>                          (9 + 12) / 71]\n#   (CAST(quadkey AS BIGINT) % 5)     count\n# 0                             0  46468834\n# 1                             2  46456313\n# 2                             1  46454483\n# 3                             3  46453305\n# Weird! No 'quadkey' % 5 == 4. \n# We can keep going. No OOM error. No need to restart our python session.\n```\nWe can keep going. There is always a chance that we will encounter an OOM for some operation. \nFor example, we will get an expected OOM error if we tried to convert the entire ~186M-row `flicker.DataFrame` into \na `pandas.DataFrame`. But, OOM errors are much less frequent than with `pyspark.pandas`. \nIn our experiments, it is more likely that your AWS S3 token will expire before you encounter an OOM error. And, \nunlike, `pyspark.pandas`, `flicker` does not run unnecessary spark queries. This makes interactive use very efficient and predictable. \n\n## Status\n`flicker` is actively being developed. While `flicker` is ready for use, please note that \nsome API may be changed in the future. Also, it is very likely that you will need a function that has not yet \nwritten in `flicker`. In such cases, you can always use the underlying PySpark DataFrame to do\nevery operation that PySpark supports. Please consider filing an issue for\nmissing functions, bugs, or unintuitive API. Happy sparking!\n\n## License\n`flicker` is available under [Apache License 2.0](https://github.com/ankur-gupta/flicker/blob/master/LICENSE).\n\n`flicker` depends on other python packages listed in [requirements.txt](https://github.com/ankur-gupta/flicker/blob/master/requirements.txt)\nwhich have their own licenses. `flicker` releases do not bundle any code from\nthe dependencies directly.\n\nThe documentation is made using [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/)\ntheme which has [MIT License](https://squidfunk.github.io/mkdocs-material/license/).",
    "bugtrack_url": null,
    "license": "Apache License Version 2.0, January 2004 http://www.apache.org/licenses/  TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION  1. Definitions.  \"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.  \"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.  \"Legal Entity\" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \"control\" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.  \"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License.  \"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.  \"Object\" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.  \"Work\" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).  \"Derivative Works\" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.  \"Contribution\" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \"submitted\" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\"  \"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.  2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.  3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.  4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:  (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and  (b) You must cause any modified files to carry prominent notices stating that You changed the files; and  (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and  (d) If the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.  You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.  5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.  6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.  7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.  8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.  9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.  END OF TERMS AND CONDITIONS  APPENDIX: How to apply the Apache License to your work.  To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets \"[]\" replaced with your own identifying information. (Don't include the brackets!)  The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same \"printed page\" as the copyright notice for easier identification within third-party archives.  Copyright [yyyy] [name of copyright owner]  Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.",
    "summary": "Provides FlickerDataFrame, a wrapper over Pyspark DataFrame to provide a pandas-like API",
    "version": "1.0.1",
    "project_urls": {
        "Homepage": "https://github.com/ankur-gupta/flicker",
        "Repository": "https://github.com/ankur-gupta/flicker.git"
    },
    "split_keywords": [
        "api",
        "dataframe",
        "pandas",
        "pyspark",
        "spark",
        "wrapper"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "701b3b0defccad303c0742413a4392deec96bb6718662fab38e246c33cf90552",
                "md5": "796cb4fa8de3f2e17a88a174c0395429",
                "sha256": "0ea982cbaa422a6838f72d8b6ec1d510390fc4656ac73fd56421ae96f8568c6a"
            },
            "downloads": -1,
            "filename": "flicker-1.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "796cb4fa8de3f2e17a88a174c0395429",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 35937,
            "upload_time": "2023-10-20T04:29:39",
            "upload_time_iso_8601": "2023-10-20T04:29:39.547349Z",
            "url": "https://files.pythonhosted.org/packages/70/1b/3b0defccad303c0742413a4392deec96bb6718662fab38e246c33cf90552/flicker-1.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "29ce0896efb1685bc9d37bd9347fbed8ff3b5cf3d7a44abc7bc0bb0fca5f53b7",
                "md5": "9ca4288a4ce4bd731112d7f2d399b985",
                "sha256": "71b498fc57d55c77724b50cf29cfb4722f7e19f67924199abf7f74e314e321e4"
            },
            "downloads": -1,
            "filename": "flicker-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "9ca4288a4ce4bd731112d7f2d399b985",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 53394,
            "upload_time": "2023-10-20T04:29:40",
            "upload_time_iso_8601": "2023-10-20T04:29:40.926053Z",
            "url": "https://files.pythonhosted.org/packages/29/ce/0896efb1685bc9d37bd9347fbed8ff3b5cf3d7a44abc7bc0bb0fca5f53b7/flicker-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-20 04:29:40",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "ankur-gupta",
    "github_project": "flicker",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "flicker"
}
        
Elapsed time: 0.14529s