pandavro


Namepandavro JSON
Version 1.7.2 PyPI version JSON
download
home_pagehttps://github.com/ynqa/pandavro
SummaryThe interface between Avro and pandas DataFrame
upload_time2023-03-31 18:14:33
maintainer
docs_urlNone
authorMakoto Ito
requires_python>=3.6.1
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # pandavro

[![Python package](https://github.com/ynqa/pandavro/actions/workflows/python-package.yml/badge.svg)](https://github.com/ynqa/pandavro/actions/workflows/python-package.yml)

The interface between Apache Avro and pandas DataFrame.

## Installation

`pandavro` is available to install from [PyPI](https://pypi.org/project/pandavro/).

```bash
$ pip install pandavro
```

## Description

It prepares like pandas APIs:

- `read_avro`
    - Read the records from Avro file and fit them into pandas DataFrame using [fastavro](https://github.com/tebeka/fastavro).
- `to_avro`
    - Write the rows of pandas DataFrame to Avro file with the original schema infer.

## What can and can't pandavro do?

Avro can represent the following kinds of types:
- Primitive types (`null`, `bool`, `int` etc.)
- Complex types (records, arrays, maps etc.)
- Logical types (annotated primitive/complex type to represent e.g. datetime)

When converting to Avro, pandavro will try to infer the schema. It will output a non-nested schema *without any indexes* set on the dataframe and it will also not try to infer if any column can be nullable so *all columns are set as nullable*, i.e. a boolean will be encoded in Avro schema as `['null', 'bool']`.

Pandavro can handle these primitive types:

| Numpy/pandas type                             | Avro primitive type |
|-----------------------------------------------|---------------------|
| np.bool_                                      | boolean             |
| np.float32                                    | float               |
| np.float64                                    | double              |
| np.unicode_                                   | string              |
| np.object_                                    | string              |
| np.int8, np.int16, np.int32                   | int                 |
| np.uint8, np.uint16, np.uint32                | "unsigned" int*     |
| np.uint64                                     | "unsigned" long*    |
| np.int64, pd.Int64Dtype                       | long                |
| pd.Int8Dtype, pd.Int16Dtype, pd.Int32Dtype    | int                 |
| pd.UInt8Dtype, pd.UInt16Dtype, pd.UInt32Dtype | "unsigned" int*     |
| pd.StringDtype**                              | string              |
| pd.BooleanDtype**                             | boolean             |

\* We represent the unsigned versions of these integers by adding the non-standard "unsigned" flag as such: `{'type': 'int', 'unsigned': True}`.  Pandas 0.24 added support for nullable integers. Writing `pd.UInt64Dtype` is not supported by fastavro.

\** Pandas 1.0.0 added support for nullable string and boolean datatypes.

Pandavro also supports these logical types:

| Numpy/pandas type                               | Avro logical type  |
|-------------------------------------------------|--------------------|
| np.datetime64, pd.DatetimeTZDtype, pd.Timestamp | timestamp-micros*  |
If a boolean column includes empty values, pandas classifies the column as having a dtype of `object` - this is accounted for in complex column handling.


And these complex types - all complex types other than 'fixed' will be classified by pandas as having a dtype of `object`, so their underlying python types are used to determine the Avro type:

| Numpy/Python type             | Avro complex type |
|-------------------------------|-------------------|
| dict, collections.OrderedDict | record            |
| list                          | array             |
| np.void                       | fixed             |

Record and array types can be arbitrarily nested within each other.

The schema definition of a record requires a unique name for the record separate from the column itself. This does not map to any concept in pandas, so for this we just append '_record' to the original column name and a number to ensure that there are zero duplicate 'name' values.

The remaining Avro complex types are not currently supported for the following reasons:
1. Enum: The closest pandas type to Avro's enum type is `pd.Categorical`, but it still is not a complete match. Possible values of the enum type can only be alphanumeric strings, whereas `pd.Categorical` values have no such limitation.
2. Map: No strictly matching concept in Python/pandas - Python dictionaries can have arbitrarily typed keys. Functionality can be essentially be achieved with the record type.
3. Union: Any column with mixed types (other than empty values/`NoneType`) are treated by pandas as having a dtype of `object`, and will be written as strings. It would be difficult to deterministically infer multiple allowed data types based solely on a column's contents.


And these logical types:

| Numpy/pandas type                               | Avro logical type                 |
|-------------------------------------------------|-----------------------------------|
| np.datetime64, pd.DatetimeTZDtype, pd.Timestamp | timestamp-micros/timezone-millis  |

Note that the timestamp must not contain any timezone (it must be naive) because Avro does not support timezones.
Timestamps are encoded as microseconds by default, but can be encoded in milliseconds by using `times_as_micros=False`

\* If passed `to_avro(..., times_as_micros=False)`, this has a millisecond resolution.

Due to [an inherent design choice in fastavro](https://github.com/fastavro/fastavro/issues/409), it interprets a *naive* datetime in the system's timezone before serializing it. This has the consequence that your *naive* datetime will not correctly roundtrip to and from an Avro file. *Always indicate a timezone* to avoid the system timezone introducing problems.

If you don't want pandavro to infer the schema but instead define it yourself, pass it using the `schema` kwarg to `to_avro`.

## Loading Pandas nullable datatypes
The nullable datatypes indicated in the table above are easily written to Avro, but loading them introduces ambiguity as we can use either the old, default or these new datatypes. We solve this by using a special keyword when loading to force conversion to these new NA-supporting datatypes:

```python
import pandavro as pdx

# Load datatypes as NA-compatible datatypes where possible
pdx.read_avro(path, na_dtypes=True)
```

This is *different* from [convert_dtypes](https://pandas.pydata.org/docs/whatsnew/v1.0.0.html#convert-dtypes-method-to-ease-use-of-supported-extension-dtypes) as it does not infer the datatype based on the actual values, but it looks at the Avro schema so is deterministic and not dependent on the actual values.

Also note that, in "normal" mode, numpy int/uint dtypes are all read back as `np.int64` due to how fastavro reads them. (This could be worked around by converting type after loading, PRs welcome.) In `na_dtypes=True` mode they are loaded correctly as Pandas NA-dtypes, but with no less than 32 bits of resolution (less is not supported by Avro so we can not infer it from the schema).

## Example

See `tests/pandavro_test.py` for more examples.

```python
import os
import numpy as np
import pandas as pd
import pandavro as pdx

OUTPUT_PATH='{}/example.avro'.format(os.path.dirname(__file__))


def main():
    df = pd.DataFrame({
        "Boolean": [True, False, True, False],
        "pdBoolean": pd.Series([True, None, True, False], dtype=pd.BooleanDtype()),
        "Float64": np.random.randn(4),
        "Int64": np.random.randint(0, 10, 4),
        "pdInt64":  pd.Series(list(np.random.randint(0, 10, 3)) + [None], dtype=pd.Int64Dtype()),
        "String": ['foo', 'bar', 'foo', 'bar'],
        "pdString": pd.Series(['foo', 'bar', 'foo', None], dtype=pd.StringDtype()),
        "DateTime64": [pd.Timestamp('20190101'), pd.Timestamp('20190102'),
                       pd.Timestamp('20190103'), pd.Timestamp('20190104')]
    })

    pdx.to_avro(OUTPUT_PATH, df)
    saved = pdx.read_avro(OUTPUT_PATH)
    print(saved)


if __name__ == '__main__':
    main()
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/ynqa/pandavro",
    "name": "pandavro",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6.1",
    "maintainer_email": "",
    "keywords": "",
    "author": "Makoto Ito",
    "author_email": "un.pensiero.vano@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/52/d3/d7d5c622f188ae874765f6f0671da049989b5ad2f3af75593691c5f2e25d/pandavro-1.7.2.tar.gz",
    "platform": null,
    "description": "# pandavro\n\n[![Python package](https://github.com/ynqa/pandavro/actions/workflows/python-package.yml/badge.svg)](https://github.com/ynqa/pandavro/actions/workflows/python-package.yml)\n\nThe interface between Apache Avro and pandas DataFrame.\n\n## Installation\n\n`pandavro` is available to install from [PyPI](https://pypi.org/project/pandavro/).\n\n```bash\n$ pip install pandavro\n```\n\n## Description\n\nIt prepares like pandas APIs:\n\n- `read_avro`\n    - Read the records from Avro file and fit them into pandas DataFrame using [fastavro](https://github.com/tebeka/fastavro).\n- `to_avro`\n    - Write the rows of pandas DataFrame to Avro file with the original schema infer.\n\n## What can and can't pandavro do?\n\nAvro can represent the following kinds of types:\n- Primitive types (`null`, `bool`, `int` etc.)\n- Complex types (records, arrays, maps etc.)\n- Logical types (annotated primitive/complex type to represent e.g. datetime)\n\nWhen converting to Avro, pandavro will try to infer the schema. It will output a non-nested schema *without any indexes* set on the dataframe and it will also not try to infer if any column can be nullable so *all columns are set as nullable*, i.e. a boolean will be encoded in Avro schema as `['null', 'bool']`.\n\nPandavro can handle these primitive types:\n\n| Numpy/pandas type                             | Avro primitive type |\n|-----------------------------------------------|---------------------|\n| np.bool_                                      | boolean             |\n| np.float32                                    | float               |\n| np.float64                                    | double              |\n| np.unicode_                                   | string              |\n| np.object_                                    | string              |\n| np.int8, np.int16, np.int32                   | int                 |\n| np.uint8, np.uint16, np.uint32                | \"unsigned\" int*     |\n| np.uint64                                     | \"unsigned\" long*    |\n| np.int64, pd.Int64Dtype                       | long                |\n| pd.Int8Dtype, pd.Int16Dtype, pd.Int32Dtype    | int                 |\n| pd.UInt8Dtype, pd.UInt16Dtype, pd.UInt32Dtype | \"unsigned\" int*     |\n| pd.StringDtype**                              | string              |\n| pd.BooleanDtype**                             | boolean             |\n\n\\* We represent the unsigned versions of these integers by adding the non-standard \"unsigned\" flag as such: `{'type': 'int', 'unsigned': True}`.  Pandas 0.24 added support for nullable integers. Writing `pd.UInt64Dtype` is not supported by fastavro.\n\n\\** Pandas 1.0.0 added support for nullable string and boolean datatypes.\n\nPandavro also supports these logical types:\n\n| Numpy/pandas type                               | Avro logical type  |\n|-------------------------------------------------|--------------------|\n| np.datetime64, pd.DatetimeTZDtype, pd.Timestamp | timestamp-micros*  |\nIf a boolean column includes empty values, pandas classifies the column as having a dtype of `object` - this is accounted for in complex column handling.\n\n\nAnd these complex types - all complex types other than 'fixed' will be classified by pandas as having a dtype of `object`, so their underlying python types are used to determine the Avro type:\n\n| Numpy/Python type             | Avro complex type |\n|-------------------------------|-------------------|\n| dict, collections.OrderedDict | record            |\n| list                          | array             |\n| np.void                       | fixed             |\n\nRecord and array types can be arbitrarily nested within each other.\n\nThe schema definition of a record requires a unique name for the record separate from the column itself. This does not map to any concept in pandas, so for this we just append '_record' to the original column name and a number to ensure that there are zero duplicate 'name' values.\n\nThe remaining Avro complex types are not currently supported for the following reasons:\n1. Enum: The closest pandas type to Avro's enum type is `pd.Categorical`, but it still is not a complete match. Possible values of the enum type can only be alphanumeric strings, whereas `pd.Categorical` values have no such limitation.\n2. Map: No strictly matching concept in Python/pandas - Python dictionaries can have arbitrarily typed keys. Functionality can be essentially be achieved with the record type.\n3. Union: Any column with mixed types (other than empty values/`NoneType`) are treated by pandas as having a dtype of `object`, and will be written as strings. It would be difficult to deterministically infer multiple allowed data types based solely on a column's contents.\n\n\nAnd these logical types:\n\n| Numpy/pandas type                               | Avro logical type                 |\n|-------------------------------------------------|-----------------------------------|\n| np.datetime64, pd.DatetimeTZDtype, pd.Timestamp | timestamp-micros/timezone-millis  |\n\nNote that the timestamp must not contain any timezone (it must be naive) because Avro does not support timezones.\nTimestamps are encoded as microseconds by default, but can be encoded in milliseconds by using `times_as_micros=False`\n\n\\* If passed `to_avro(..., times_as_micros=False)`, this has a millisecond resolution.\n\nDue to [an inherent design choice in fastavro](https://github.com/fastavro/fastavro/issues/409), it interprets a *naive* datetime in the system's timezone before serializing it. This has the consequence that your *naive* datetime will not correctly roundtrip to and from an Avro file. *Always indicate a timezone* to avoid the system timezone introducing problems.\n\nIf you don't want pandavro to infer the schema but instead define it yourself, pass it using the `schema` kwarg to `to_avro`.\n\n## Loading Pandas nullable datatypes\nThe nullable datatypes indicated in the table above are easily written to Avro, but loading them introduces ambiguity as we can use either the old, default or these new datatypes. We solve this by using a special keyword when loading to force conversion to these new NA-supporting datatypes:\n\n```python\nimport pandavro as pdx\n\n# Load datatypes as NA-compatible datatypes where possible\npdx.read_avro(path, na_dtypes=True)\n```\n\nThis is *different* from [convert_dtypes](https://pandas.pydata.org/docs/whatsnew/v1.0.0.html#convert-dtypes-method-to-ease-use-of-supported-extension-dtypes) as it does not infer the datatype based on the actual values, but it looks at the Avro schema so is deterministic and not dependent on the actual values.\n\nAlso note that, in \"normal\" mode, numpy int/uint dtypes are all read back as `np.int64` due to how fastavro reads them. (This could be worked around by converting type after loading, PRs welcome.) In `na_dtypes=True` mode they are loaded correctly as Pandas NA-dtypes, but with no less than 32 bits of resolution (less is not supported by Avro so we can not infer it from the schema).\n\n## Example\n\nSee `tests/pandavro_test.py` for more examples.\n\n```python\nimport os\nimport numpy as np\nimport pandas as pd\nimport pandavro as pdx\n\nOUTPUT_PATH='{}/example.avro'.format(os.path.dirname(__file__))\n\n\ndef main():\n    df = pd.DataFrame({\n        \"Boolean\": [True, False, True, False],\n        \"pdBoolean\": pd.Series([True, None, True, False], dtype=pd.BooleanDtype()),\n        \"Float64\": np.random.randn(4),\n        \"Int64\": np.random.randint(0, 10, 4),\n        \"pdInt64\":  pd.Series(list(np.random.randint(0, 10, 3)) + [None], dtype=pd.Int64Dtype()),\n        \"String\": ['foo', 'bar', 'foo', 'bar'],\n        \"pdString\": pd.Series(['foo', 'bar', 'foo', None], dtype=pd.StringDtype()),\n        \"DateTime64\": [pd.Timestamp('20190101'), pd.Timestamp('20190102'),\n                       pd.Timestamp('20190103'), pd.Timestamp('20190104')]\n    })\n\n    pdx.to_avro(OUTPUT_PATH, df)\n    saved = pdx.read_avro(OUTPUT_PATH)\n    print(saved)\n\n\nif __name__ == '__main__':\n    main()\n```\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "The interface between Avro and pandas DataFrame",
    "version": "1.7.2",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5e3816d192b6fec75d4416fb923e6f09f0768200452b3cdc4c6d9ccfa451df88",
                "md5": "e3a7856932b096e28db6acf1c454368a",
                "sha256": "5b4a2fbc86fb2b102e5b2b24490084e4775a5ac546fc8981931abecf6bb4a34b"
            },
            "downloads": -1,
            "filename": "pandavro-1.7.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e3a7856932b096e28db6acf1c454368a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6.1",
            "size": 8829,
            "upload_time": "2023-03-31T18:14:32",
            "upload_time_iso_8601": "2023-03-31T18:14:32.743881Z",
            "url": "https://files.pythonhosted.org/packages/5e/38/16d192b6fec75d4416fb923e6f09f0768200452b3cdc4c6d9ccfa451df88/pandavro-1.7.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "52d3d7d5c622f188ae874765f6f0671da049989b5ad2f3af75593691c5f2e25d",
                "md5": "1d238c7cb5a59a30c9acc87f4db58012",
                "sha256": "4f2b7b6823522f54e8bfe33c091fb29898349892b70634f46c928e6a42a76e69"
            },
            "downloads": -1,
            "filename": "pandavro-1.7.2.tar.gz",
            "has_sig": false,
            "md5_digest": "1d238c7cb5a59a30c9acc87f4db58012",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6.1",
            "size": 8806,
            "upload_time": "2023-03-31T18:14:33",
            "upload_time_iso_8601": "2023-03-31T18:14:33.993658Z",
            "url": "https://files.pythonhosted.org/packages/52/d3/d7d5c622f188ae874765f6f0671da049989b5ad2f3af75593691c5f2e25d/pandavro-1.7.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-03-31 18:14:33",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "ynqa",
    "github_project": "pandavro",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pandavro"
}
        
Elapsed time: 0.09169s