Contributing to pandas

Table of contents:

Where to start?

All contributions, bug reports, bug fixes, documentation improvements,enhancements, and ideas are welcome.

If you are brand new to pandas or open-source development, we recommend goingthrough the GitHub “issues” tabto find issues that interest you. There are a number of issues listed under Docsand good first issuewhere you could start out. Once you’ve found an interesting issue, you canreturn here to get your development environment setup.

Feel free to ask questions on the mailing list or on Gitter.

Bug reports and enhancement requests

Bug reports are an important part of making pandas more stable. Having a complete bug reportwill allow others to reproduce the bug and provide insight into fixing. Seethis stackoverflow article andthis blogpostfor tips on writing a good bug report.

Trying the bug-producing code out on the master branch is often a worthwhile exerciseto confirm the bug still exists. It is also worth searching existing bug reports and pull requeststo see if the issue has already been reported and/or fixed.

Bug reports must:

  • Include a short, self-contained Python snippet reproducing the problem.You can format the code nicely by using GitHub Flavored Markdown:
  1. ```python
  2. >>> from pandas import DataFrame
  3. >>> df = DataFrame(...)
  4. ...
  5. ```
  • Include the full version string of pandas and its dependencies. You can use the built-in function:
  1. >>> import pandas as pd
  2. >>> pd.show_versions()
  • Explain why the current behavior is wrong/not desired and what you expect instead.

The issue will then show up to the pandas community and be open to comments/ideas from others.

Working with the code

Now that you have an issue you want to fix, enhancement to add, or documentation to improve,you need to learn how to work with GitHub and the pandas code base.

Version control, Git, and GitHub

To the new user, working with Git is one of the more daunting aspects of contributing to pandas.It can very quickly become overwhelming, but sticking to the guidelines below will help keep the processstraightforward and mostly trouble free. As always, if you are having difficulties pleasefeel free to ask for help.

The code is hosted on GitHub. Tocontribute you will need to sign up for a free GitHub account. We use Git forversion control to allow many people to work together on the project.

Some great resources for learning Git:

Getting started with Git

GitHub has instructions for installing git,setting up your SSH key, and configuring git. All these steps need to be completed beforeyou can work seamlessly between your local repository and GitHub.

Forking

You will need your own fork to work on the code. Go to the pandas projectpage and hit the Fork button. You willwant to clone your fork to your machine:

  1. git clone https://github.com/your-user-name/pandas.git pandas-yourname
  2. cd pandas-yourname
  3. git remote add upstream https://github.com/pandas-dev/pandas.git

This creates the directory pandas-yourname and connects your repository tothe upstream (main project) pandas repository.

Creating a development environment

To test out code changes, you’ll need to build pandas from source, whichrequires a C compiler and Python environment. If you’re making documentationchanges, you can skip to Contributing to the documentation but you won’t be ableto build the documentation locally before pushing your changes.

Installing a C compiler

Pandas uses C extensions (mostly written using Cython) to speed up certainoperations. To install pandas from source, you need to compile these Cextensions, which means you need a C compiler. This process depends on whichplatform you’re using. Follow the CPython contributing guide for getting acompiler installed. You don’t need to do any of the ./configure or makesteps; you only need to install the compiler.

For Windows developers, when using Python 3.5 and later, it is sufficient toinstall Visual Studio 2017 with thePython development workload and the Python native development toolsoption. Otherwise, the following links may be helpful.

Let us know if you have any difficulties by opening an issue or reaching out onGitter.

Creating a Python environment

Now that you have a C compiler, create an isolated pandas developmentenvironment:

We’ll now kick off a three-step process:

  • Install the build dependencies
  • Build and install pandas
  • Install the optional dependencies
  1. # Create and activate the build environment
  2. conda env create -f environment.yml
  3. conda activate pandas-dev
  4.  
  5. # or with older versions of Anaconda:
  6. source activate pandas-dev
  7.  
  8. # Build and install pandas
  9. python setup.py build_ext --inplace -j 4
  10. python -m pip install -e .

At this point you should be able to import pandas from your locally built version:

  1. $ python # start an interpreter
  2. >>> import pandas
  3. >>> print(pandas.__version__)
  4. 0.22.0.dev0+29.g4ad6d4d74

This will create the new environment, and not touch any of your existing environments,nor any existing Python installation.

To view your environments:

  1. conda info -e

To return to your root environment:

  1. conda deactivate

See the full conda docs here.

Creating a Python environment (pip)

If you aren’t using conda for your development environment, follow these instructions.You’ll need to have at least python3.5 installed on your system.

  1. # Create a virtual environment
  2. # Use an ENV_DIR of your choice. We'll use ~/virtualenvs/pandas-dev
  3. # Any parent directories should already exist
  4. python3 -m venv ~/virtualenvs/pandas-dev
  5. # Activate the virtualenv
  6. . ~/virtualenvs/pandas-dev/bin/activate
  7.  
  8. # Install the build dependencies
  9. python -m pip install -r requirements-dev.txt
  10.  
  11. # Build and install pandas
  12. python setup.py build_ext --inplace -j 4
  13. python -m pip install -e .

Creating a branch

You want your master branch to reflect only production-ready code, so create afeature branch for making your changes. For example:

  1. git branch shiny-new-feature
  2. git checkout shiny-new-feature

The above can be simplified to:

  1. git checkout -b shiny-new-feature

This changes your working directory to the shiny-new-feature branch. Keep anychanges in this branch specific to one bug or feature so it is clearwhat the branch brings to pandas. You can have many shiny-new-featuresand switch in between them using the git checkout command.

When creating this branch, make sure your master branch is up to date withthe latest upstream master version. To update your local master branch, youcan do:

  1. git checkout master
  2. git pull upstream master --ff-only

When you want to update the feature branch with changes in master afteryou created the branch, check the section onupdating a PR.

Contributing to the documentation

Contributing to the documentation benefits everyone who uses pandas.We encourage you to help us improve the documentation, andyou don’t have to be an expert on pandas to do so! In fact,there are sections of the docs that are worse off after being written byexperts. If something in the docs doesn’t make sense to you, updating therelevant section after you figure it out is a great way to ensure it will helpthe next person.

Documentation:

About the pandas documentation

The documentation is written in reStructuredText, which is almost like writingin plain English, and built using Sphinx. TheSphinx Documentation has an excellent introduction to reST. Review the Sphinx docs to perform morecomplex changes to the documentation as well.

Some other important things to know about the docs:

  • The pandas documentation consists of two parts: the docstrings in the codeitself and the docs in this folder doc/.

The docstrings provide a clear explanation of the usage of the individualfunctions, while the documentation in this folder consists of tutorial-likeoverviews per topic together with some other information (what’s new,installation, etc).

  • The docstrings follow a pandas convention, based on the Numpy DocstringStandard. Follow the pandas docstring guide for detailedinstructions on how to write a correct docstring.
  • The tutorials make heavy use of the ipython directive sphinx extension.This directive lets you put code in the documentation which will be runduring the doc build. For example:
  1. .. ipython:: python
  2.  
  3. x = 2
  4. x**3

will be rendered as:

  1. In [1]: x = 2
  2.  
  3. In [2]: x**3
  4. Out[2]: 8

Almost all code examples in the docs are run (and the output saved) during thedoc build. This approach means that code examples will always be up to date,but it does make the doc building a bit more complex.

  • Our API documentation in doc/source/api.rst houses the auto-generateddocumentation from the docstrings. For classes, there are a few subtletiesaround controlling which methods and attributes have pages auto-generated.

We have two autosummary templates for classes.

  • _templates/autosummary/class.rst. Use this when you want toautomatically generate a page for every public method and attribute on theclass. The Attributes and Methods sections will be automaticallyadded to the class’ rendered documentation by numpydoc. See DataFramefor an example.
  • _templates/autosummary/class_without_autosummary. Use this when youwant to pick a subset of methods / attributes to auto-generate pages for.When using this template, you should include an Attributes andMethods section in the class docstring. See CategoricalIndex for anexample.Every method should be included in a toctree in api.rst, else Sphinxwill emit a warning.

Note

The .rst files are used to automatically generate Markdown and HTML versionsof the docs. For this reason, please do not edit CONTRIBUTING.md directly,but instead make any changes to doc/source/development/contributing.rst. Then, togenerate CONTRIBUTING.md, use pandocwith the following command:

  1. pandoc doc/source/development/contributing.rst -t markdown_github > CONTRIBUTING.md

The utility script scripts/validate_docstrings.py can be used to get a csvsummary of the API documentation. And also validate common errors in the docstringof a specific class, function or method. The summary also compares the list ofmethods documented in doc/source/api.rst (which is used to generatethe API Reference page)and the actual public methods.This will identify methods documented in doc/source/api.rst that are not actuallyclass methods, and existing methods that are not documented in doc/source/api.rst.

Updating a pandas docstring

When improving a single function or method’s docstring, it is not necessarilyneeded to build the full documentation (see next section).However, there is a script that checks a docstring (for example for the DataFrame.mean method):

  1. python scripts/validate_docstrings.py pandas.DataFrame.mean

This script will indicate some formatting errors if present, and will alsorun and test the examples included in the docstring.Check the pandas docstring guide for a detailed guideon how to format the docstring.

The examples in the docstring (‘doctests’) must be valid Python code,that in a deterministic way returns the presented output, and that can becopied and run by users. This can be checked with the script above, and isalso tested on Travis. A failing doctest will be a blocker for merging a PR.Check the examples section in the docstring guidefor some tips and tricks to get the doctests passing.

When doing a PR with a docstring update, it is good to post theoutput of the validation script in a comment on github.

How to build the pandas documentation

Requirements

First, you need to have a development environment to be able to build pandas(see the docs on creating a development environment above).

Building the documentation

So how do you build the docs? Navigate to your localdoc/ directory in the console and run:

  1. python make.py html

Then you can find the HTML output in the folder doc/build/html/.

The first time you build the docs, it will take quite a while because it has to runall the code examples and build all the generated docstring pages. In subsequentevocations, sphinx will try to only build the pages that have been modified.

If you want to do a full clean build, do:

  1. python make.py clean
  2. python make.py html

You can tell make.py to compile only a single section of the docs, greatlyreducing the turn-around time for checking your changes.

  1. # omit autosummary and API section
  2. python make.py clean
  3. python make.py --no-api
  4.  
  5. # compile the docs with only a single section, relative to the "source" folder.
  6. # For example, compiling only this guide (docs/source/development/contributing.rst)
  7. python make.py clean
  8. python make.py --single development/contributing.rst
  9.  
  10. # compile the reference docs for a single function
  11. python make.py clean
  12. python make.py --single pandas.DataFrame.join

For comparison, a full documentation build may take 15 minutes, but a singlesection may take 15 seconds. Subsequent builds, which only process portionsyou have changed, will be faster.

You can also specify to use multiple cores to speed up the documentation build:

  1. python make.py html --num-jobs 4

Open the following file in a web browser to see the full documentation youjust built:

  1. doc/build/html/index.html

And you’ll have the satisfaction of seeing your new and improved documentation!

Building master branch documentation

When pull requests are merged into the pandas master branch, the main parts ofthe documentation are also built by Travis-CI. These docs are then hosted here, see alsothe Continuous Integration section.

Contributing to the code base

Code Base:

Code standards

Writing good code is not just about what you write. It is also about how youwrite it. During Continuous Integration testing, severaltools will be run to check your code for stylistic errors.Generating any warnings will cause the test to fail.Thus, good style is a requirement for submitting code to pandas.

There is a tool in pandas to help contributors verify their changes beforecontributing them to the project:

  1. ./ci/code_checks.sh

The script verifies the linting of code files, it looks for common mistake patterns(like missing spaces around sphinx directives that make the documentation notbeing rendered properly) and it also validates the doctests. It is possible torun the checks independently by using the parameters lint, patterns anddoctests (e.g. ./ci/code_checks.sh lint).

In addition, because a lot of people use our library, it is important that wedo not make sudden changes to the code that could have the potential to breaka lot of user code as a result, that is, we need it to be as _backwards compatible_as possible to avoid mass breakages.

Additional standards are outlined on the code style wikipage.

Optional dependencies

Optional dependencies (e.g. matplotlib) should be imported with the private helperpandas.compat._optional.import_optional_dependency. This ensures aconsistent error message when the dependency is not met.

All methods using an optional dependency should include a test asserting that anImportError is raised when the optional dependency is not found. This testshould be skipped if the library is present.

All optional dependencies should be documented inOptional dependencies and the minimum required version should beset in the pandas.compat._optional.VERSIONS dict.

C (cpplint)

pandas uses the Googlestandard. Google provides an open source style checker called cpplint, but weuse a fork of it that can be found here.Here are some of the more common cpplint issues:

  • we restrict line-length to 80 characters to promote readability
  • every header file must include a header guard to avoid name collisions if re-included

Continuous Integration will run thecpplint tooland report any stylistic errors in your code. Therefore, it is helpful beforesubmitting code to run the check yourself:

  1. cpplint --extensions=c,h --headers=h --filter=-readability/casting,-runtime/int,-build/include_subdir modified-c-file

You can also run this command on an entire directory if necessary:

  1. cpplint --extensions=c,h --headers=h --filter=-readability/casting,-runtime/int,-build/include_subdir --recursive modified-c-directory

To make your commits compliant with this standard, you can install theClangFormat tool, which can bedownloaded here. To configure, in your home directory,run the following command:

  1. clang-format style=google -dump-config > .clang-format

Then modify the file to ensure that any indentation width parameters are at least four.Once configured, you can run the tool as follows:

  1. clang-format modified-c-file

This will output what your file will look like if the changes are made, and to applythem, run the following command:

  1. clang-format -i modified-c-file

To run the tool on an entire directory, you can run the following analogous commands:

  1. clang-format modified-c-directory/*.c modified-c-directory/*.h
  2. clang-format -i modified-c-directory/*.c modified-c-directory/*.h

Do note that this tool is best-effort, meaning that it will try to correct asmany errors as possible, but it may not correct all of them. Thus, it isrecommended that you run cpplint to double check and make any other stylefixes manually.

Python (PEP8 / black)

pandas follows the PEP8 standardand uses Black andFlake8 to ensure a consistent codeformat throughout the project.

Continuous Integration will run those tools andreport any stylistic errors in your code. Therefore, it is helpful beforesubmitting code to run the check yourself:

  1. black pandas
  2. git diff upstream/master -u -- "*.py" | flake8 --diff

to auto-format your code. Additionally, many editors have plugins that willapply black as you edit files.

Optionally, you may wish to setup pre-commit hooksto automatically run black and flake8 when you make a git commit. Thiscan be done by installing pre-commit:

  1. pip install pre-commit

and then running:

  1. pre-commit install

from the root of the pandas repository. Now black and flake8 will be runeach time you commit changes. You can skip these checks withgit commit —no-verify.

This command will catch any stylistic errors in your changes specifically, butbe beware it may not catch all of them. For example, if you delete the onlyusage of an imported function, it is stylistically incorrect to import anunused function. However, style-checking the diff will not catch this becausethe actual import is not part of the diff. Thus, for completeness, you shouldrun this command, though it will take longer:

  1. git diff upstream/master --name-only -- "*.py" | xargs -r flake8

Note that on OSX, the -r flag is not available, so you have to omit it andrun this slightly modified command:

  1. git diff upstream/master --name-only -- "*.py" | xargs flake8

Windows does not support the xargs command (unless installed for examplevia the MinGW toolchain), but one can imitate thebehaviour as follows:

  1. for /f %i in ('git diff upstream/master --name-only -- "*.py"') do flake8 %i

This will get all the files being changed by the PR (and ending with .py),and run flake8 on them, one after the other.

Import formatting

pandas uses isort to standardise importformatting across the codebase.

A guide to import layout as per pep8 can be found here.

A summary of our current import sections ( in order ):

  • Future
  • Python Standard Library
  • Third Party
  • pandas.libs, pandas.compat, pandas.util.*, pandas.errors (largely not dependent on pandas.core)
  • pandas.core.dtypes (largely not dependent on the rest of pandas.core)
  • Rest of pandas.core.*
  • Non-core pandas.io, pandas.plotting, pandas.tseries
  • Local application/library specific imports

Imports are alphabetically sorted within these sections.

As part of Continuous Integration checks we run:

  1. isort --recursive --check-only pandas

to check that imports are correctly formatted as per the setup.cfg.

If you see output like the below in Continuous Integration checks:

  1. Check import format using isort
  2. ERROR: /home/travis/build/pandas-dev/pandas/pandas/io/pytables.py Imports are incorrectly sorted
  3. Check import format using isort DONE
  4. The command "ci/code_checks.sh" exited with 1

You should run:

  1. isort pandas/io/pytables.py

to automatically format imports correctly. This will modify your local copy of the files.

The –recursive flag can be passed to sort all files in a directory.

You can then verify the changes look ok, then git commit and push.

Backwards compatibility

Please try to maintain backward compatibility. pandas has lots of users with lots ofexisting code, so don’t break it if at all possible. If you think breakage is required,clearly state why as part of the pull request. Also, be careful when changing methodsignatures and add deprecation warnings where needed. Also, add the deprecated sphinxdirective to the deprecated functions or methods.

If a function with the same arguments as the one being deprecated exist, you can usethe pandas.util._decorators.deprecate:

  1. from pandas.util._decorators import deprecate
  2.  
  3. deprecate('old_func', 'new_func', '0.21.0')

Otherwise, you need to do it manually:

  1. import warnings
  2.  
  3.  
  4. def old_func():
  5. """Summary of the function.
  6.  
  7. .. deprecated:: 0.21.0
  8. Use new_func instead.
  9. """
  10. warnings.warn('Use new_func instead.', FutureWarning, stacklevel=2)
  11. new_func()
  12.  
  13.  
  14. def new_func():
  15. pass

You’ll also need to

  • Write a new test that asserts a warning is issued when calling with the deprecated argument
  • Update all of pandas existing tests and code to use the new argumentSee Testing warnings for more.

Testing with continuous integration

The pandas test suite will run automatically on Travis-CI andAzure Pipelinescontinuous integration services, once your pull request is submitted.However, if you wish to run the test suite on a branch prior to submitting the pull request,then the continuous integration services need to be hooked to your GitHub repository. Instructions are herefor Travis-CI andAzure Pipelines.

A pull-request will be considered for merging when you have an all ‘green’ build. If any tests are failing,then you will get a red ‘X’, where you can click through to see the individual failed tests.This is an example of a green build.../_images/ci.png

Note

Each time you push to your fork, a new run of the tests will be triggered on the CI.You can enable the auto-cancel feature, which removes any non-currently-running tests for that same pull-request, forTravis-CI here.

Test-driven development/code writing

pandas is serious about testing and strongly encourages contributors to embracetest-driven development (TDD).This development process “relies on the repetition of a very short development cycle:first the developer writes an (initially failing) automated test case that defines a desiredimprovement or new function, then produces the minimum amount of code to pass that test.”So, before actually writing any code, you should write your tests. Often the test can betaken from the original GitHub issue. However, it is always worth considering additionaluse cases and writing corresponding tests.

Adding tests is one of the most common requests after code is pushed to pandas. Therefore,it is worth getting in the habit of writing tests ahead of time so this is never an issue.

Like many packages, pandas uses pytest and the convenientextensions in numpy.testing.

Note

The earliest supported pytest version is 4.0.2.

Writing tests

All tests should go into the tests subdirectory of the specific package.This folder contains many current examples of tests, and we suggest looking to these forinspiration. If your test requires working with files ornetwork connectivity, there is more information on the testing page of the wiki.

The pandas.util.testing module has many special assert functions thatmake it easier to make statements about whether Series or DataFrame objects areequivalent. The easiest way to verify that your code is correct is toexplicitly construct the result you expect, then compare the actual result tothe expected correct result:

  1. def test_pivot(self):
  2. data = {
  3. 'index' : ['A', 'B', 'C', 'C', 'B', 'A'],
  4. 'columns' : ['One', 'One', 'One', 'Two', 'Two', 'Two'],
  5. 'values' : [1., 2., 3., 3., 2., 1.]
  6. }
  7.  
  8. frame = DataFrame(data)
  9. pivoted = frame.pivot(index='index', columns='columns', values='values')
  10.  
  11. expected = DataFrame({
  12. 'One' : {'A' : 1., 'B' : 2., 'C' : 3.},
  13. 'Two' : {'A' : 1., 'B' : 2., 'C' : 3.}
  14. })
  15.  
  16. assert_frame_equal(pivoted, expected)

Transitioning to pytest

pandas existing test structure is mostly classed based, meaning that you will typically find tests wrapped in a class.

  1. class TestReallyCoolFeature:
  2. pass

Going forward, we are moving to a more functional style using the pytest framework, which offers a richer testingframework that will facilitate testing and developing. Thus, instead of writing test classes, we will write test functions like this:

  1. def test_really_cool_feature():
  2. pass

Using pytest

Here is an example of a self-contained set of tests that illustrate multiple features that we like to use.

  • functional style: tests are like test* and _only take arguments that are either fixtures or parameters
  • pytest.mark can be used to set metadata on test functions, e.g. skip or xfail.
  • using parametrize: allow testing of multiple cases
  • to set a mark on a parameter, pytest.param(…, marks=…) syntax should be used
  • fixture, code for object construction, on a per-test basis
  • using bare assert for scalars and truth-testing
  • tm.assert_series_equal (and its counter part tm.assert_frame_equal), for pandas object comparisons.
  • the typical pattern of constructing an expected and comparing versus the result

We would name this file test_cool_feature.py and put in an appropriate place in the pandas/tests/ structure.

  1. import pytest
  2. import numpy as np
  3. import pandas as pd
  4.  
  5.  
  6. @pytest.mark.parametrize('dtype', ['int8', 'int16', 'int32', 'int64'])
  7. def test_dtypes(dtype):
  8. assert str(np.dtype(dtype)) == dtype
  9.  
  10.  
  11. @pytest.mark.parametrize(
  12. 'dtype', ['float32', pytest.param('int16', marks=pytest.mark.skip),
  13. pytest.param('int32', marks=pytest.mark.xfail(
  14. reason='to show how it works'))])
  15. def test_mark(dtype):
  16. assert str(np.dtype(dtype)) == 'float32'
  17.  
  18.  
  19. @pytest.fixture
  20. def series():
  21. return pd.Series([1, 2, 3])
  22.  
  23.  
  24. @pytest.fixture(params=['int8', 'int16', 'int32', 'int64'])
  25. def dtype(request):
  26. return request.param
  27.  
  28.  
  29. def test_series(series, dtype):
  30. result = series.astype(dtype)
  31. assert result.dtype == dtype
  32.  
  33. expected = pd.Series([1, 2, 3], dtype=dtype)
  34. tm.assert_series_equal(result, expected)

A test run of this yields

  1. ((pandas) bash-3.2$ pytest test_cool_feature.py -v
  2. =========================== test session starts ===========================
  3. platform darwin -- Python 3.6.2, pytest-3.6.0, py-1.4.31, pluggy-0.4.0
  4. collected 11 items
  5.  
  6. tester.py::test_dtypes[int8] PASSED
  7. tester.py::test_dtypes[int16] PASSED
  8. tester.py::test_dtypes[int32] PASSED
  9. tester.py::test_dtypes[int64] PASSED
  10. tester.py::test_mark[float32] PASSED
  11. tester.py::test_mark[int16] SKIPPED
  12. tester.py::test_mark[int32] xfail
  13. tester.py::test_series[int8] PASSED
  14. tester.py::test_series[int16] PASSED
  15. tester.py::test_series[int32] PASSED
  16. tester.py::test_series[int64] PASSED

Tests that we have parametrized are now accessible via the test name, for example we could run these with -k int8 to sub-select only those tests which match int8.

  1. ((pandas) bash-3.2$ pytest test_cool_feature.py -v -k int8
  2. =========================== test session starts ===========================
  3. platform darwin -- Python 3.6.2, pytest-3.6.0, py-1.4.31, pluggy-0.4.0
  4. collected 11 items
  5.  
  6. test_cool_feature.py::test_dtypes[int8] PASSED
  7. test_cool_feature.py::test_series[int8] PASSED

Using hypothesis

Hypothesis is a library for property-based testing. Instead of explicitlyparametrizing a test, you can describe all valid inputs and let Hypothesistry to find a failing input. Even better, no matter how many random examplesit tries, Hypothesis always reports a single minimal counterexample to yourassertions - often an example that you would never have thought to test.

See Getting Started with Hypothesisfor more of an introduction, then refer to the Hypothesis documentationfor details.

  1. import json
  2. from hypothesis import given, strategies as st
  3.  
  4. any_json_value = st.deferred(lambda: st.one_of(
  5. st.none(), st.booleans(), st.floats(allow_nan=False), st.text(),
  6. st.lists(any_json_value), st.dictionaries(st.text(), any_json_value)
  7. ))
  8.  
  9.  
  10. @given(value=any_json_value)
  11. def test_json_roundtrip(value):
  12. result = json.loads(json.dumps(value))
  13. assert value == result

This test shows off several useful features of Hypothesis, as well asdemonstrating a good use-case: checking properties that should hold overa large or complicated domain of inputs.

To keep the Pandas test suite running quickly, parametrized tests arepreferred if the inputs or logic are simple, with Hypothesis tests reservedfor cases with complex logic or where there are too many combinations ofoptions or subtle interactions to test (or think of!) all of them.

Testing warnings

By default, one of pandas CI workers will fail if any unhandled warnings are emitted.

If your change involves checking that a warning is actually emitted, usetm.assert_produces_warning(ExpectedWarning).

  1. import pandas.util.testing as tm
  2.  
  3.  
  4. df = pd.DataFrame()
  5. with tm.assert_produces_warning(FutureWarning):
  6. df.some_operation()

We prefer this to the pytest.warns context manager because ours checks that the warning’sstacklevel is set correctly. The stacklevel is what ensure the user’s file name and line numberis printed in the warning, rather than something internal to pandas. It represents the number offunction calls from user code (e.g. df.some_operation()) to the function that actually emitsthe warning. Our linter will fail the build if you use pytest.warns in a test.

If you have a test that would emit a warning, but you aren’t actually testing thewarning itself (say because it’s going to be removed in the future, or because we’rematching a 3rd-party library’s behavior), then use pytest.mark.filterwarnings toignore the error.

  1. @pytest.mark.filterwarnings("ignore:msg:category")def test_thing(self):

If the test generates a warning of class category whose message startswith msg, the warning will be ignored and the test will pass.

If you need finer-grained control, you can use Python’s usualwarnings moduleto control whether a warning is ignored / raised at different places withina single test.

  1. with warnings.catch_warnings():
  2. warnings.simplefilter("ignore", FutureWarning)
  3. # Or use warnings.filterwarnings(...)

Alternatively, consider breaking up the unit test.

Running the test suite

The tests can then be run directly inside your Git clone (without having toinstall pandas) by typing:

  1. pytest pandas

The tests suite is exhaustive and takes around 20 minutes to run. Often it isworth running only a subset of tests first around your changes before running theentire suite.

The easiest way to do this is with:

  1. pytest pandas/path/to/test.py -k regex_matching_test_name

Or with one of the following constructs:

  1. pytest pandas/tests/[test-module].py
  2. pytest pandas/tests/[test-module].py::[TestClass]
  3. pytest pandas/tests/[test-module].py::[TestClass]::[test_method]

Using pytest-xdist, one canspeed up local testing on multicore machines. To use this feature, you willneed to install pytest-xdist via:

  1. pip install pytest-xdist

Two scripts are provided to assist with this. These scripts distributetesting across 4 threads.

On Unix variants, one can type:

  1. test_fast.sh

On Windows, one can type:

  1. test_fast.bat

This can significantly reduce the time it takes to locally run tests beforesubmitting a pull request.

For more, see the pytest documentation.

New in version 0.20.0.

Furthermore one can run

  1. pd.test()

with an imported pandas to run tests similarly.

Running the performance test suite

Performance matters and it is worth considering whether your code has introducedperformance regressions. pandas is in the process of migrating toasv benchmarksto enable easy monitoring of the performance of critical pandas operations.These benchmarks are all found in the pandas/asv_bench directory. asvsupports both python2 and python3.

To use all features of asv, you will need either conda orvirtualenv. For more details please check the asv installationwebpage.

To install asv:

  1. pip install git+https://github.com/spacetelescope/asv

If you need to run a benchmark, change your directory to asv_bench/ and run:

  1. asv continuous -f 1.1 upstream/master HEAD

You can replace HEAD with the name of the branch you are working on,and report benchmarks that changed by more than 10%.The command uses conda by default for creating the benchmarkenvironments. If you want to use virtualenv instead, write:

  1. asv continuous -f 1.1 -E virtualenv upstream/master HEAD

The -E virtualenv option should be added to all asv commandsthat run benchmarks. The default value is defined in asv.conf.json.

Running the full test suite can take up to one hour and use up to 3GB of RAM.Usually it is sufficient to paste only a subset of the results into the pullrequest to show that the committed changes do not cause unexpected performanceregressions. You can run specific benchmarks using the -b flag, whichtakes a regular expression. For example, this will only run tests from apandas/asv_bench/benchmarks/groupby.py file:

  1. asv continuous -f 1.1 upstream/master HEAD -b ^groupby

If you want to only run a specific group of tests from a file, you can do itusing . as a separator. For example:

  1. asv continuous -f 1.1 upstream/master HEAD -b groupby.GroupByMethods

will only run the GroupByMethods benchmark defined in groupby.py.

You can also run the benchmark suite using the version of pandasalready installed in your current Python environment. This can beuseful if you do not have virtualenv or conda, or are using thesetup.py develop approach discussed above; for the in-place buildyou need to set PYTHONPATH, e.g.PYTHONPATH="$PWD/.." asv [remaining arguments].You can run benchmarks using an existing Pythonenvironment by:

  1. asv run -e -E existing

or, to use a specific Python interpreter,:

  1. asv run -e -E existing:python3.5

This will display stderr from the benchmarks, and use your localpython that comes from your $PATH.

Information on how to write a benchmark and how to use asv can be found in theasv documentation.

Documenting your code

Changes should be reflected in the release notes located in doc/source/whatsnew/vx.y.z.rst.This file contains an ongoing change log for each release. Add an entry to this file todocument your fix, enhancement or (unavoidable) breaking change. Make sure to include theGitHub issue number when adding your entry (using :issue:1234 where 1234 is theissue/pull request number).

If your code is an enhancement, it is most likely necessary to add usageexamples to the existing documentation. This can be done following the sectionregarding documentation above.Further, to let users know when this feature was added, the versionaddeddirective is used. The sphinx syntax for that is:

  1. .. versionadded:: 0.21.0

This will put the text New in version 0.21.0 wherever you put the sphinxdirective. This should also be put in the docstring when adding a new functionor method (example)or a new keyword argument (example).

Contributing your changes to pandas

Committing your code

Keep style fixes to a separate commit to make your pull request more readable.

Once you’ve made changes, you can see them by typing:

  1. git status

If you have created a new file, it is not being tracked by git. Add it by typing:

  1. git add path/to/file-to-be-added.py

Doing ‘git status’ again should give something like:

  1. # On branch shiny-new-feature
  2. #
  3. # modified: /relative/path/to/file-you-added.py
  4. #

Finally, commit your changes to your local repository with an explanatory message. _Pandas_uses a convention for commit message prefixes and layout. Here aresome common prefixes along with general guidelines for when to use them:

  • ENH: Enhancement, new functionality
  • BUG: Bug fix
  • DOC: Additions/updates to documentation
  • TST: Additions/updates to tests
  • BLD: Updates to the build process/scripts
  • PERF: Performance improvement
  • CLN: Code cleanup

The following defines how a commit message should be structured. Please reference therelevant GitHub issues in your commit message using GH1234 or #1234. Either styleis fine, but the former is generally preferred:

  • a subject line with < 80 chars.
  • One blank line.
  • Optionally, a commit message body.

Now you can commit your changes in your local repository:

  1. git commit -m

Pushing your changes

When you want your changes to appear publicly on your GitHub page, push yourforked feature branch’s commits:

  1. git push origin shiny-new-feature

Here origin is the default name given to your remote repository on GitHub.You can see the remote repositories:

  1. git remote -v

If you added the upstream repository as described above you will see somethinglike:

  1. origin git@github.com:yourname/pandas.git (fetch)
  2. origin git@github.com:yourname/pandas.git (push)
  3. upstream git://github.com/pandas-dev/pandas.git (fetch)
  4. upstream git://github.com/pandas-dev/pandas.git (push)

Now your code is on GitHub, but it is not yet a part of the pandas project. For that tohappen, a pull request needs to be submitted on GitHub.

Review your code

When you’re ready to ask for a code review, file a pull request. Before you do, onceagain make sure that you have followed all the guidelines outlined in this documentregarding code style, tests, performance tests, and documentation. You should alsodouble check your branch changes against the branch it was based on:

  • Navigate to your repository on GitHub – https://github.com/your-user-name/pandas
  • Click on Branches
  • Click on the Compare button for your feature branch
  • Select the base and compare branches, if necessary. This will be master andshiny-new-feature, respectively.

Finally, make the pull request

If everything looks good, you are ready to make a pull request. A pull request is howcode from a local repository becomes available to the GitHub community and can be lookedat and eventually merged into the master version. This pull request and its associatedchanges will eventually be committed to the master branch and available in the nextrelease. To submit a pull request:

  • Navigate to your repository on GitHub
  • Click on the Pull Request button
  • You can then click on Commits and Files Changed to make sure everything looksokay one last time
  • Write a description of your changes in the Preview Discussion tab
  • Click Send Pull Request.This request then goes to the repository maintainers, and they will reviewthe code.

Updating your pull request

Based on the review you get on your pull request, you will probably need to makesome changes to the code. In that case, you can make them in your branch,add a new commit to that branch, push it to GitHub, and the pull request will beautomatically updated. Pushing them to GitHub again is done by:

  1. git push origin shiny-new-feature

This will automatically update your pull request with the latest code and restart theContinuous Integration tests.

Another reason you might need to update your pull request is to solve conflictswith changes that have been merged into the master branch since you opened yourpull request.

To do this, you need to “merge upstream master” in your branch:

  1. git checkout shiny-new-feature
  2. git fetch upstream
  3. git merge upstream/master

If there are no conflicts (or they could be fixed automatically), a file with adefault commit message will open, and you can simply save and quit this file.

If there are merge conflicts, you need to solve those conflicts. See forexample at https://help.github.com/articles/resolving-a-merge-conflict-using-the-command-line/for an explanation on how to do this.Once the conflicts are merged and the files where the conflicts were solved areadded, you can run git commit to save those fixes.

If you have uncommitted changes at the moment you want to update the branch withmaster, you will need to stash them prior to updating (see thestash docs).This will effectively store your changes and they can be reapplied after updating.

After the feature branch has been update locally, you can now update your pullrequest by pushing to the branch on GitHub:

  1. git push origin shiny-new-feature

Delete your merged branch (optional)

Once your feature branch is accepted into upstream, you’ll probably want to get rid ofthe branch. First, merge upstream master into your branch so git knows it is safe todelete your branch:

  1. git fetch upstream
  2. git checkout master
  3. git merge upstream/master

Then you can do:

  1. git branch -d shiny-new-feature

Make sure you use a lower-case -d, or else git won’t warn you if your featurebranch has not actually been merged.

The branch will still exist on GitHub, so to delete it there do:

  1. git push origin --delete shiny-new-feature