Как загрузить пандас в питон
Перейти к содержимому

Как загрузить пандас в питон

  • автор:

Установка¶

Проще всего установить pandas в составе Anaconda — кроссплатформенного дистрибутива для анализа данных и научных вычислений. Это рекомендуемый метод установки для большинства пользователей.

Здесь вы также найдете инструкции по установке из исходников, с помощью PyPI, ActivePython, различных дистрибутивов Linux и версию для разработки.

Поддержка версий Python¶

Официально поддерживается Python 3.8, 3.9 и 3.10.

Установка pandas¶

Установка с помощью Anaconda¶

Установка pandas и остальной части стека NumPy и SciPy может быть немного сложной для неопытных пользователей.

Проще всего установить не только pandas, но и Python и самые популярные пакеты, составляющие стек SciPy (IPython , NumPy, Matplotlib и так далее) с использованием Anaconda — кроссплатформенного (Linux, macOS, Windows) дистрибутива Python для анализа данных и научных вычислений.

После запуска установщика пользователь получит доступ к pandas и остальной части стека SciPy без необходимости устанавливать что-либо еще и без необходимости ждать, пока какое-либо программное обеспечение будет скомпилировано.

Инструкции по установке Anaconda можно найти здесь.

Полный список пакетов, доступных в составе дистрибутива Anaconda, можно найти здесь.

Еще одним преимуществом установки Anaconda является то, что вам не нужны права администратора для ее установки. Anaconda может быть установлена в домашнем каталоге пользователя, что упрощает удаление Anaconda в случае необходимости (просто удалите эту папку).

Установка с помощью Miniconda¶

В предыдущем разделе было описано, как установить pandas в составе дистрибутива Anaconda. Однако этот подход означает, что вы установите более сотни пакетов и предполагает загрузку установщика, размер которого составляет несколько сотен мегабайт.

Если вы хотите иметь больший контроль над пакетами или пропускная способность интернета у вас ограничена, то установка pandas с помощью Miniconda может вам подойти лучше.

Conda — это менеджер пакетов, на котором построен дистрибутив Anaconda. Это менеджер пакетов, который является одновременно кроссплатформенным и независимым от языка (он похож на комбинацию pip и virtualenv).

Miniconda позволяет вам создать минимальную автономную установку Python, а затем использовать команды Conda для установки дополнительных пакетов (см. краткое руководство по Miniconda на русском).

Сначала вам нужно установить Conda, и загрузка и запуск Miniconda решит эту задачу. Установщик можно найти здесь.

Следующим шагом является создание новой среды conda. Виртуальная среда conda похожа на ту, которая создается virtualenv, она позволяет указать конкретную версию Python и набор библиотек. Запустите следующие команды из окна терминала:

Это создаст минимальную среду, в которой будет установлен только Python. Чтобы активировать эту среду, запустите:

В Windows команда следующая:

Последним шагом необходимо установить pandas. Это можно сделать с помощью следующей команды:

Установить определенную версию pandas:

Установить другие пакеты, например, IPython:

Установить полный дистрибутив Anaconda:

Если вам нужны пакеты, доступные для pip, но не для conda, установите pip, а затем используйте pip для установки этих пакетов:

Установка из PyPI¶

pandas можно установить через pip из PyPI.

У вас должен быть pip>=19.3 для установки из PyPI.

Установка с ActivePython¶

Инструкции по установке ActivePython можно найти здесь. Версии 2.7, 3.5 и 3.6 включают pandas.

Установка с помощью менеджера пакетов вашего дистрибутива Linux.¶

Команды в этой таблице установят pandas для Python 3 из вашего дистрибутива.

Ссылка на скачивание / репозиторий

Команда для установки

sudo apt-get install python3-pandas

нестабильный (последние пакеты)

sudo apt-get install python3-pandas

sudo apt-get install python3-pandas

zypper in python3-pandas

dnf install python3-pandas

yum install python3-pandas

Однако пакеты в менеджерах пакетов linux часто отстают на несколько версий, поэтому, чтобы получить новейшую версию pandas, рекомендуется устанавливать ее с помощью команд pip или conda , описанных выше.

Обработка ошибок импорта¶

Если вы столкнулись с ошибкой ImportError, это обычно означает, что Python не смог найти pandas в списке доступных библиотек. Внутри Python есть список каталогов, в которых он ищет пакеты. Вы можете получить список этих каталогов с помощью команды:

Одна из возможных причин ошибки — это если Python в системе установлен более одного раза, и pandas не установлен в том Python, который вы используете на текущий момент. В Linux/Mac вы можете запустить what python на своем терминале, и он сообщит вам, какой Python вы используете. Если это что-то вроде «/usr/bin/python», вы используете Python из системы, что не рекомендуется.

Настоятельно рекомендуется использовать conda для быстрой установки и обновления пакетов и зависимостей. Вы можете найти простые инструкции по установке pandas в этом документе.

Установка из исходников¶

Полные инструкции по сборке из исходного дерева git см. в Contributing guide. Если вы хотите создать среду разработки pandas, смотрите Creating a development environment.

Запуск набора тестов¶

pandas оснащен исчерпывающим набором модульных тестов, покрывающих около 97% кодовой базы на момент написания этой статьи. Чтобы запустить его на своем компьютере и удостовериться, что все работает (и что у вас установлены все зависимости, программные и аппаратные), убедитесь, что у вас есть pytest >= 6.0 и Hypothesis >= 3.58, затем запустите:

Installation#

The easiest way to install pandas is to install it as part of the Anaconda distribution, a cross platform distribution for data analysis and scientific computing. This is the recommended installation method for most users.

Instructions for installing from source, PyPI, ActivePython, various Linux distributions, or a development version are also provided.

Python version support#

Officially Python 3.8, 3.9, 3.10 and 3.11.

Installing pandas#

Installing with Anaconda#

Installing pandas and the rest of the NumPy and SciPy stack can be a little difficult for inexperienced users.

The simplest way to install not only pandas, but Python and the most popular packages that make up the SciPy stack (IPython, NumPy, Matplotlib, …) is with Anaconda, a cross-platform (Linux, macOS, Windows) Python distribution for data analytics and scientific computing.

After running the installer, the user will have access to pandas and the rest of the SciPy stack without needing to install anything else, and without needing to wait for any software to be compiled.

Installation instructions for Anaconda can be found here.

A full list of the packages available as part of the Anaconda distribution can be found here.

Another advantage to installing Anaconda is that you don’t need admin rights to install it. Anaconda can install in the user’s home directory, which makes it trivial to delete Anaconda if you decide (just delete that folder).

Installing with Miniconda#

The previous section outlined how to get pandas installed as part of the Anaconda distribution. However this approach means you will install well over one hundred packages and involves downloading the installer which is a few hundred megabytes in size.

If you want to have more control on which packages, or have a limited internet bandwidth, then installing pandas with Miniconda may be a better solution.

Conda is the package manager that the Anaconda distribution is built upon. It is a package manager that is both cross-platform and language agnostic (it can play a similar role to a pip and virtualenv combination).

Miniconda allows you to create a minimal self contained Python installation, and then use the Conda command to install additional packages.

First you will need Conda to be installed and downloading and running the Miniconda will do this for you. The installer can be found here

The next step is to create a new conda environment. A conda environment is like a virtualenv that allows you to specify a specific version of Python and set of libraries. Run the following commands from a terminal window:

This will create a minimal environment with only Python installed in it. To put your self inside this environment run:

On Windows the command is:

The final step required is to install pandas. This can be done with the following command:

To install a specific pandas version:

To install other packages, IPython for example:

To install the full Anaconda distribution:

If you need packages that are available to pip but not conda, then install pip, and then use pip to install those packages:

Installing from PyPI#

pandas can be installed via pip from PyPI.

You must have pip>=19.3 to install from PyPI.

Installing with ActivePython#

Installation instructions for ActivePython can be found here. Versions 2.7, 3.5 and 3.6 include pandas.

Installing using your Linux distribution’s package manager.#

The commands in this table will install pandas for Python 3 from your distribution.

Name already in use

pandas / doc / source / getting_started / install.rst

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

52 contributors

Users who have contributed to this file

  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

The easiest way to install pandas is to install it as part of the Anaconda distribution, a cross platform distribution for data analysis and scientific computing. This is the recommended installation method for most users.

Instructions for installing from source, PyPI, ActivePython, various Linux distributions, or a development version are also provided.

Python version support

Officially Python 3.8, 3.9, 3.10 and 3.11.

Installing with Anaconda

Installing pandas and the rest of the NumPy and SciPy stack can be a little difficult for inexperienced users.

The simplest way to install not only pandas, but Python and the most popular packages that make up the SciPy stack (IPython, NumPy, Matplotlib, . ) is with Anaconda, a cross-platform (Linux, macOS, Windows) Python distribution for data analytics and scientific computing.

After running the installer, the user will have access to pandas and the rest of the SciPy stack without needing to install anything else, and without needing to wait for any software to be compiled.

Installation instructions for Anaconda can be found here.

A full list of the packages available as part of the Anaconda distribution can be found here.

Another advantage to installing Anaconda is that you don’t need admin rights to install it. Anaconda can install in the user’s home directory, which makes it trivial to delete Anaconda if you decide (just delete that folder).

Installing with Miniconda

The previous section outlined how to get pandas installed as part of the Anaconda distribution. However this approach means you will install well over one hundred packages and involves downloading the installer which is a few hundred megabytes in size.

If you want to have more control on which packages, or have a limited internet bandwidth, then installing pandas with Miniconda may be a better solution.

Conda is the package manager that the Anaconda distribution is built upon. It is a package manager that is both cross-platform and language agnostic (it can play a similar role to a pip and virtualenv combination).

Miniconda allows you to create a minimal self contained Python installation, and then use the Conda command to install additional packages.

First you will need Conda to be installed and downloading and running the Miniconda will do this for you. The installer can be found here

The next step is to create a new conda environment. A conda environment is like a virtualenv that allows you to specify a specific version of Python and set of libraries. Run the following commands from a terminal window:

This will create a minimal environment with only Python installed in it. To put your self inside this environment run:

On Windows the command is:

The final step required is to install pandas. This can be done with the following command:

To install a specific pandas version:

To install other packages, IPython for example:

To install the full Anaconda distribution:

If you need packages that are available to pip but not conda, then install pip, and then use pip to install those packages:

Installing from PyPI

pandas can be installed via pip from PyPI.

You must have pip>=19.3 to install from PyPI.

pandas can also be installed with sets of optional dependencies to enable certain functionality. For example, to install pandas with the optional dependencies to read Excel files.

The full list of extras that can be installed can be found in the :ref:`dependency section.<install.optional_dependencies>`

Installing with ActivePython

Installation instructions for ActivePython can be found here. Versions 2.7, 3.5 and 3.6 include pandas.

Installing using your Linux distribution’s package manager.

The commands in this table will install pandas for Python 3 from your distribution.

Distribution Status Download / Repository Link Install method
Debian stable official Debian repository sudo apt-get install python3-pandas
Debian & Ubuntu unstable (latest packages) NeuroDebian sudo apt-get install python3-pandas
Ubuntu stable official Ubuntu repository sudo apt-get install python3-pandas
OpenSuse stable OpenSuse Repository zypper in python3-pandas
Fedora stable official Fedora repository dnf install python3-pandas
Centos/RHEL stable EPEL repository yum install python3-pandas

However, the packages in the linux package managers are often a few versions behind, so to get the newest version of pandas, it’s recommended to install using the pip or conda methods described above.

If you encounter an ImportError, it usually means that Python couldn’t find pandas in the list of available libraries. Python internally has a list of directories it searches through, to find packages. You can obtain these directories with:

One way you could be encountering this error is if you have multiple Python installations on your system and you don’t have pandas installed in the Python installation you’re currently using. In Linux/Mac you can run which python on your terminal and it will tell you which Python installation you’re using. If it’s something like «/usr/bin/python», you’re using the Python from the system, which is not recommended.

It is highly recommended to use conda , for quick installation and for package and dependency updates. You can find simple installation instructions for pandas in this document: installation instructions </getting_started.html> .

Installing from source

See the :ref:`contributing guide <contributing>` for complete instructions on building from the git source tree. Further, see :ref:`creating a development environment <contributing_environment>` if you wish to create a pandas development environment.

Installing the development version of pandas

Installing a nightly build is the quickest way to:

  • Try a new feature that will be shipped in the next release (that is, a feature from a pull-request that was recently merged to the main branch).
  • Check whether a bug you encountered has been fixed since the last release.

You can install the nightly build of pandas using the scipy-wheels-nightly index from the PyPI registry of anaconda.org with the following command:

Note that first uninstalling pandas might be required to be able to install nightly builds:

Running the test suite

pandas is equipped with an exhaustive set of unit tests, covering about 97% of the code base as of this writing. To run it on your machine to verify that everything is working (and that you have all of the dependencies, soft and hard, installed), make sure you have pytest >= 7.0 and Hypothesis >= 6.34.2, then run:

This is just an example of what information is shown. You might see a slightly different result as what is shown above.

pandas requires the following dependencies.

Package Minimum supported version
NumPy 1.20.3
python-dateutil 2.8.2
pytz 2020.1

pandas has many optional dependencies that are only used for specific methods. For example, :func:`pandas.read_hdf` requires the pytables package, while :meth:`DataFrame.to_markdown` requires the tabulate package. If the optional dependency is not installed, pandas will raise an ImportError when the method requiring that dependency is called.

If using pip, optional pandas dependencies can be installed or managed in a file (e.g. requirements.txt or pyproject.toml) as optional extras (e.g.,«pandas[performance, aws]>=1.5.0«). All optional dependencies can be installed with pandas[all] , and specific sets of dependencies are listed in the sections below.

Performance dependencies (recommended)

You are highly encouraged to install these libraries, as they provide speed improvements, especially when working with large data sets.

Installable with pip install «pandas[performance]»

Dependency Minimum Version pip extra Notes
numexpr 2.7.3 performance Accelerates certain numerical operations by using uses multiple cores as well as smart chunking and caching to achieve large speedups
bottleneck 1.3.2 performance Accelerates certain types of nan by using specialized cython routines to achieve large speedup.
numba 0.53.1 performance Alternative execution engine for operations that accept engine=»numba» using a JIT compiler that translates Python functions to optimized machine code using the LLVM compiler.

Installable with pip install «pandas[timezone]»

Allows the use of zoneinfo timezones with pandas. Note: You only need to install the pypi package if your system does not already provide the IANA tz database. However, the minimum tzdata version still applies, even if it is not enforced through an error.

If you would like to keep your system tzdata version updated, it is recommended to use the tzdata package from conda-forge.

Installable with pip install «pandas[plot, output_formatting]» .

Dependency Minimum Version pip extra Notes
matplotlib 3.6.1 plot Plotting library
Jinja2 3.0.0 output_formatting Conditional formatting with DataFrame.style
tabulate 0.8.9 output_formatting Printing in Markdown-friendly format (see tabulate)

Installable with pip install «pandas[computation]» .

Dependency Minimum Version pip extra Notes
SciPy 1.7.1 computation Miscellaneous statistical functions
xarray 0.21.0 computation pandas-like API for N-dimensional data

Installable with pip install «pandas[excel]» .

Dependency Minimum Version pip extra Notes
xlrd 2.0.1 excel Reading Excel
xlsxwriter 1.4.3 excel Writing Excel
openpyxl 3.0.7 excel Reading / writing for xlsx files
pyxlsb 1.0.8 excel Reading for xlsb files

Installable with pip install «pandas[html]» .

Dependency Minimum Version pip extra Notes
BeautifulSoup4 4.9.3 html HTML parser for read_html
html5lib 1.1 html HTML parser for read_html
lxml 4.6.3 html HTML parser for read_html

One of the following combinations of libraries is needed to use the top-level :func:`

    and html5lib and lxml and html5lib and lxml
  • Only lxml, although see :ref:`HTML Table Parsing <io.html.gotchas>` for reasons as to why you should probably not take this approach.

    if you install BeautifulSoup4 you must install either lxml or html5lib or both. :func:`

Installable with pip install «pandas[xml]» .

Dependency Minimum Version pip extra Notes
lxml 4.6.3 xml XML parser for read_xml and tree builder for to_xml

Installable with pip install «pandas[postgresql, mysql, sql-other]» .

Dependency Minimum Version pip extra Notes
SQLAlchemy 1.4.16 postgresql, mysql, sql-other SQL support for databases other than sqlite
psycopg2 2.8.6 postgresql PostgreSQL engine for sqlalchemy
pymysql 1.0.2 mysql MySQL engine for sqlalchemy

Other data sources

Installable with pip install «pandas[hdf5, parquet, feather, spss, excel]»

Библиотека Pandas в Python

Pandas – это библиотека с открытым исходным кодом на Python. Она предоставляет готовые к использованию высокопроизводительные структуры данных и инструменты анализа данных.

  • Модуль Pandas работает поверх NumPy и широко используется для обработки и анализа данных.
  • NumPy – это низкоуровневая структура данных, которая поддерживает многомерные массивы и широкий спектр математических операций с массивами. Pandas имеет интерфейс более высокого уровня. Он также обеспечивает оптимизированное согласование табличных данных и мощную функциональность временных рядов.
  • DataFrame – это ключевая структура данных в Pandas. Это позволяет нам хранить и обрабатывать табличные данные, как двумерную структуру данных.
  • Pandas предоставляет богатый набор функций для DataFrame. Например, выравнивание данных, статистика данных, нарезка, группировка, объединение, объединение данных и т.д.

Установка и начало работы с Pandas

Для установки модуля Pandas вам потребуется Python 2.7 и выше.

Если вы используете conda, вы можете установить его, используя команду ниже.

Если вы используете PIP, выполните команду ниже, чтобы установить модуль pandas.

Модуль Pandas в Python

Чтобы импортировать Pandas и NumPy в свой скрипт Python, добавьте следующий фрагмент кода:

Поскольку Pandas зависит от библиотеки NumPy, нам нужно импортировать эту зависимость.

Структуры данных

Модуль Pandas предоставляет 3 структуры данных, а именно:

  • Series: это одномерный массив неизменного размера, подобный структуре, имеющей однородные данные.
  • DataFrames: это двумерная табличная структура с изменяемым размером и неоднородно типизированными столбцами.
  • Panel: это трехмерный массив с изменяемым размером.

DataFrame

DataFrame – самая важная и широко используемая структура данных, а также стандартный способ хранения данных. Она содержит данные, выровненные по строкам и столбцам, как в таблице SQL или в базе данных электронной таблицы.

Мы можем либо жестко закодировать данные в DataFrame, либо импортировать файл CSV, файл tsv, файл Excel, таблицу SQL и т.д.

Мы можем использовать приведенный ниже конструктор для создания объекта DataFrame.

Ниже приводится краткое описание параметров:

  • data – создать объект DataFrame из входных данных. Это может быть список, dict, series, Numpy ndarrays или даже любой другой DataFrame;
  • index – имеет метки строк;
  • columns – используются для создания подписей столбцов;
  • dtype – используется для указания типа данных каждого столбца, необязательный параметр;
  • copy – используется для копирования данных, если есть.

Есть много способов создать DataFrame. Мы можем создать объект из словарей или списка словарей. Мы также можем создать его из списка кортежей, CSV, файла Excel и т.д.

Давайте запустим простой код для создания DataFrame из списка словарей.

Модуль Dataframe Python

Первый шаг – создать словарь. Второй шаг – передать словарь в качестве аргумента в метод DataFrame(). Последний шаг – распечатать DataFrame.

Как видите, DataFrame можно сравнить с таблицей, имеющей неоднородное значение. Кроме того, можно изменить размер.

Мы предоставили данные в виде карты, и ключи карты рассматриваются Pandas, как метки строк.

Индекс отображается в крайнем левом столбце и имеет метки строк. Заголовок столбца и данные отображаются в виде таблицы.

Также возможно создавать индексированные DataFrames. Это можно сделать, настроив параметр индекса.

Импорт данных из CSV

Мы также можем создать DataFrame, импортировав файл CSV. Файл CSV – это текстовый файл с одной записью данных в каждой строке. Значения в записи разделяются символом «запятая».

Pandas предоставляет полезный метод с именем read_csv() для чтения содержимого файла CSV.

Например, мы можем создать файл с именем «cities.csv», содержащий подробную информацию о городах Индии. Файл CSV хранится в том же каталоге, что и сценарии Python. Этот файл можно импортировать с помощью:

Наша цель – загрузить данные и проанализировать их, чтобы сделать выводы. Итак, мы можем использовать любой удобный способ загрузки данных.

Проверка данных

Head

Tail

Точно так же print (df.dtypes) печатает типы данных.

Dtype

print (df.index) печатает index.

df.index

print (df.columns) печатает столбцы DataFrame.

df.columns

print (df.values) отображает значения таблицы.

df.value

1. Получение статистической сводки записей

Функция df.describe()

Функция df.describe() отображает статистическую сводку вместе с типом данных.

2. Сортировка записей

Сортировка записей

3. Нарезка записей

Нарезка записей

Slicemultiplecol

Slicerows

Интересной особенностью библиотеки Pandas является выбор данных на основе меток строк и столбцов с помощью функции iloc [0].

Часто для анализа может потребоваться всего несколько столбцов. Мы также можем выбрать по индексу, используя loc [‘index_one’]).

Например, чтобы выбрать вторую строку, мы можем использовать df.iloc [1 ,:].

Допустим, нам нужно выбрать второй элемент второго столбца. Это можно сделать с помощью функции df.iloc [1,1]. В этом примере функция df.iloc [1,1] отображает в качестве вывода «Мумбаи».

4. Фильтрация данных

Для фильтрации по условию можно использовать любой оператор сравнения.

Фильтрация данных

Filter

5. Переименование столбца

Аргумент inplace = True вносит изменения в DataFrame.

Переименование столбца

6. Сбор данных

Наука о данных включает в себя обработку данных, чтобы данные могли хорошо работать с алгоритмами данных. Data Wrangling – это процесс обработки данных, такой как слияние, группировка и конкатенация.

Библиотека Pandas предоставляет полезные функции, такие как merge(), groupby() и concat() для поддержки задач Data Wrangling.

Сбор данных

Wrangling 2

а. merge()

Функция merge()

Мы видим, что функция merge() возвращает строки из обоих DataFrames, имеющих то же значение столбца, которое использовалось при слиянии.

b. Группировка

Поле «Employee_name» со значением «Meera» сгруппировано по столбцу «Employee_name». Пример вывода приведен ниже:

Группировка

c. Конкатенация

Конкатенация

Создание DataFrame, переход Dict в Series

Пример создания серии

Мы создали серию. Вы можете видеть, что отображаются 2 столбца. Первый столбец содержит значения индекса, начиная с 0. Второй столбец содержит элементы, переданные как серии.

Можно создать DataFrame, передав словарь Series. Давайте создадим DataFrame, который формируется путем объединения и передачи индексов ряда.

Создание DataFrame

Для первой серии, поскольку мы не указали метку ‘d’, возвращается NaN.

Выбор столбца, добавление и удаление

Приведенный выше код печатает только столбец «Matches played» в DataFrame.

Выбор столбца

Добавление

Удаление

Заключение

В этом руководстве у нас было краткое введение в библиотеку Pandas в Python. Мы также сделали практические примеры, чтобы раскрыть возможности библиотеки, используемой в области науки о данных. Мы также рассмотрели различные структуры данных в библиотеке Python.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *