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

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

  • автор:

Data Manipulation with Pandas

In the previous chapter, we dove into detail on NumPy and its ndarray object, which provides efficient storage and manipulation of dense typed arrays in Python. Here we’ll build on this knowledge by looking in detail at the data structures provided by the Pandas library. Pandas is a newer package built on top of NumPy, and provides an efficient implementation of a DataFrame . DataFrame s are essentially multidimensional arrays with attached row and column labels, and often with heterogeneous types and/or missing data. As well as offering a convenient storage interface for labeled data, Pandas implements a number of powerful data operations familiar to users of both database frameworks and spreadsheet programs.

As we saw, NumPy’s ndarray data structure provides essential features for the type of clean, well-organized data typically seen in numerical computing tasks. While it serves this purpose very well, its limitations become clear when we need more flexibility (e.g., attaching labels to data, working with missing data, etc.) and when attempting operations that do not map well to element-wise broadcasting (e.g., groupings, pivots, etc.), each of which is an important piece of analyzing the less structured data available in many forms in the world around us. Pandas, and in particular its Series and DataFrame objects, builds on the NumPy array structure and provides efficient access to these sorts of «data munging» tasks that occupy much of a data scientist’s time.

In this chapter, we will focus on the mechanics of using Series , DataFrame , and related structures effectively. We will use examples drawn from real datasets where appropriate, but these examples are not necessarily the focus.

Installing and Using Pandas¶

Installation of Pandas on your system requires NumPy to be installed, and if building the library from source, requires the appropriate tools to compile the C and Cython sources on which Pandas is built. Details on this installation can be found in the Pandas documentation. If you followed the advice outlined in the Preface and used the Anaconda stack, you already have Pandas installed.

Установка¶

Проще всего установить 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, затем запустите:

How to Install Pandas in Python?

When analyzing data using Python, Pandas is a game changer, one of the most popular and commonly used tools in data analytics. What's nice about Pandas is that it takes data from a CSV or TSV file or a SQL database and generates a Python object with rows and columns called a data frame, which looks remarkably similar to a table in statistics tools like Excel. Working with this is far more convenient than dealing with lists and/or dictionaries. However, to work with it, we must first learn how to install Pandas on our system and then install Pandas on our devices.

Introduction

NumPy may considerably simplify our lives when dealing with large amounts of numerical data. However, there are occasions when various data are involved, and Numpy is not usually the ideal choice. Pandas come in helpful in such cases. It has numerous application possibilities, but the preferable situation is to read files that are not solely numerical, such as " .csv " or " .xlsx " files which include numerical data and textual metadata about those data.

Before delving into the intricacies of the Pandas Library, we must first grasp the idea of NumPy arrays. But why NumPy? Because NumPy is the foundation of the open-source software package Pandas.

Now that you're familiar with NumPy let's move on to Pandas.

Introduction to Pandas

So, what exactly is Pandas? Pandas is an acronym that stands for " Python Data Analysis Library." Pandas is a widely used library for managing tabular data, data manipulation, and analysis based on NumPy. The fact that Pandas saves the information as a Python object containing rows and columns, comparable to data saved in Excel files, is probably its best feature. Also, we can quickly view our data in this manner, which makes our task much easier than dealing with data in the form of lists or dictionaries. Also, it has an advantage over NumPy in that it can handle numerous data types (e.g., strings), rather than only numerical data; nonetheless, this makes it slower than NumPy.

Following a quick introduction to Pandas, let us look at the prerequisites before installing Pandas on our system.

Prerequisites

To "work with" Pandas, we must first install it. Python 3.5.x or later is also required. It requires Python 3.6, 3.7, or 3.8 as a prerequisite for installation. It also relies on other libraries (such as NumPy) and has optional dependencies (like Matplotlib for plotting). As a result, the simplest approach to get Pandas up and running is to use PyPi or Conda to install it. Conda is the package manager upon which the Anaconda distribution is based. It is a cross-platform and language-independent package manager.

Now let us look at how we can install Pandas on our system. Before installing the Pandas package, ensure that you have installed Python or Anaconda and have established the environment variables to access Python, pip, or pip3 commands through the command line, shell, or terminal according to your operating system.

Install Pandas on Windows

As previously said, we can update or get Pandas to the newest version in various methods based on how we installed Python. First, let's look at installing Pandas on Windows using the pip and conda commands.

Method 1: Using pip

It's a package installation tool that simplifies the installation of Python modules and frameworks. Pip will be installed with Python by default if you have a later version of Python available (greater than Python 3.5.x). If you're using an earlier version of Python, you'll need to install pip before you can install Pandas. The simplest method to accomplish this is to update to the most recent version of Python, which can be found at this link.

Step 1: Launch Command Prompt

To open the start menu, use the Windows key on your keyboard or click the Start button. For example, when you type "cmd" the Command Prompt app should display in the start menu, and once you can view the command prompt app, launch the app. Alternatively, you may hit the Windows key + r to bring up the "RUN" box, where you can input “cmd” and then press enter. It will also launch the Command prompt.

Step 2: Enter the command

After you open the command prompt, the following step is to enter the needed command to begin the pip installation. For example, enter the command shown below.

This will start the pip installation. After downloading the necessary files, Pandas will be set to operate on your computer. You can employ Pandas in your Python projects once the installation has been completed.

Method 2: Using conda

Installing Pandas using Anaconda is the best option if you are unfamiliar with command-line programming. Anaconda is a sophisticated Python distribution that provides access to various libraries besides Pandas. Anaconda will become increasingly handy as you learn further about Python.

Step 1 : Download Anaconda

To install Anaconda, go to this page and then click on the "Download" button on the right.

The file of the latest version of Python available for your Windows PC will start downloading.

Step 2 : Install Anaconda

Start your installation from the website by clicking the "Next" button.

Then, click the "I Agree" option to accept the licensing agreement.

Then, pick the user accounts for whom Pandas should be installed. We proceeded by selecting the recommended "Just Me" option.

In the wizard's concluding stage, you must specify where the distribution will be downloaded.

Finally, under the advanced installation options area, tick the "Add Anaconda to my PATH environment variable" and "Register Anaconda3 as my preferred Python 3.x (x over here denotes whatever the current version could be)" choices.

The installation of Anaconda will begin when you click the "Install" button. When the setup is finished, you will see the "Installation Complete" screen within a few minutes. It appears as follows:

The Pandas libraries on your Windows system will all be available now. This is due to the fact Anaconda automatically downloads all of the key libraries during installation.

Install Pandas on Linux

Depending on the package management of your Linux distribution, there are three ways to install pandas. We can either :

  1. install it with pip,
  2. install it with conda, or
  3. download it from the package manager's repository.

Installing pandas through the distribution's package manager's repository is untrustworthy since the repository frequently contains an earlier version of pandas. Furthermore, Conda will require you to set it up before installing pandas, which will lengthen the procedure. As a result, installing Pandas using pip is the ideal option since it installs the most recent version and eliminates the need to go through multiple steps to set up another required tool.

For Ubuntu Users

Method 1 : Using Pip

This method is quite identical to the one described in the section "Install Pandas on Windows."

  • Step 1: Install pip

Running the following line in your terminal will install pip3 on your Linux system:

Remember that because pip requires Python 3, Python 3 must be downloaded on your Linux system. When you execute the command, you may see something like this:

The program will also download " python-pip-whl " and " python3-wheel, " as you can see. The "Wheel" package format is integrated into Python.

To begin the installation process, type the " Y " key. When the procedure is finished, you can go to the next stage.

  • Step 2 : Install Pandas

Now that pip is installed on your Linux system, and you can use it to install Pandas. You only need to execute the following command in the terminal:

When the command completes, Pandas will be installed on your Linux system.

Method 2: Using Anaconda

If Anaconda is pre-installed on your Linux computer, proceed to step 2. For example, to download Anaconda on Ubuntu 20.04, follow the following step:

  • Step 1 : Install Anaconda

To begin installing Anaconda, you first must install the necessary installer. To do so, go to this website and scroll a little. To the right of the website is a section labeled "Get Additional Installers." Select the Linux icon.

Scroll to the "Anaconda Installers" portion of the website. Locate the installation for your Linux system and right-click on it. Then, select the "Copy link address" option.

You must use "wget" to install the script now that you have copied the URL to the bash installer with the ".sh" suffix to your clipboard.

Launch your terminal and browse to your home directory using the cd command. Next, make a directory called "temporary" following. Then, go to the newly formed temporary folder and use the "wget" command as described below to install the installation.

The script is huge, so you'll have to wait a while to install it.

After downloading the script, you must run it to set up Anaconda3 on your system. Make sure you're in the temporary directory before running any commands. After that, execute the following command:

The licensing agreement will be shown, and you must approve it to install Anaconda. Then, you must allow Anaconda to be added to your machine's PATH variable. Anaconda will be invoked anytime you put " $ python " in your terminal after being added to your machine's PATH.

For Fedora Users

Fedora users can acquire the newest version of Pandas by running the following command in their system's terminal.

Using your Linux distribution's package manager to install Pandas

Python Pandas library can be installed in various methods, although Linux distributions such as Ubuntu, Debian, CentOS/RHEL, Fedora, OpenSuse, and others include the pandas package in their official repositories. The pandas package may be installed using the apt, yum, or dnf package managers. Please see the following table for a better understanding:

Sr No. Distribution Official Link Bash Command
1 Debian Official Debian Repository Link sudo apt-get install python3-pandas
2 Ubuntu Official Ubuntu Repository Link sudo apt-get install python3-pandas
3 OpenSuse Official OpenSuse Repository Link zypper in python3-pandas
4 Centos/RHEL Official EPEL Repository Link yum install python3-pandas
5 Fedora Official Fedora Repository Link dnf install python3-pandas

Install Pandas on Mac OS

You may install pandas on Mac OS using pip or conda as you did on Windows or Linux.

Method 1 : Using pip

Assuming you installed pip successfully on our Mac OS device. Once pip is installed on your device, run the following command in your terminal to install Pandas.

If you're not the root user, sudo may not function well because sudo downloads Python packages in the root directory, where you might need access to write files. If you wish to download to a specific user, use the "—user" option.

Vola! Now Pandas have been installed on your device.

Advanced Usage

Using Anaconda

Installing pandas and the rest of the NumPy and SciPy stack might be challenging for novice users. However, anaconda, a cross-platform (Linux, macOS, Windows) Python distribution for data analytics and scientific computing, is the simplest method to install not just pandas but also Python and the most popular programs comprising the SciPy stack (IPython, NumPy, Matplotlib. ). After executing the installer, the user will have access to pandas and the rest of the SciPy stack without installing or waiting for any software to be constructed.

To get a clear image of how to download Anaconda for your system, follow the instructions outlined in the article earlier based on your operating system.

Using Miniconda

In the preceding sections, we described how to install pandas as a package of the Anaconda distribution. However, that method requires installing well over a hundred libraries and installing the installer, which is a few hundred mbs in size.

If you want greater control over whatever library you wish to install or have restricted internet speed, installing pandas using Miniconda may be preferable.

You may obtain your miniconda installation from the following Link. You can select the operating system and version that you want to install. You now have conda setup on your device after installing miniconda, which means you may install Pandas with the following command:

Using PyPi

Pandas may be installed via PyPI using pip. Run the following command in your terminal or command line to install pandas on your device.

Using ActivePython

ActivePython , like Anaconda, is a powerful Python distribution that, in addition to Pandas, gives access to a large range of libraries. This implies that after we install ActivePython, the pandas library will be downloaded automatically as part of the ActivePython installation. You may browse to the following website, search for your operating system, and then follow the procedures to get the current version of Python as well as the Pandas package on your system.

Installing directly from the source

The Pandas library's source code is available at this link, and it may be downloaded from there by following the methods outlined below:

Downloading from the git repository necessitates a current Cython installation. So, first, you should download the MinGW compiler suite on Windows. Once the property has been configured, perform the following commands from the command line:

It should be noted that if you launch an interpreter in the source directory, you will be unable to import pandas until you construct the C extensions in place using the command line as follow:

Obtaining the newest version of Pandas using the pip or conda command rather than installing straight from the source as it lengthens the process.

How to fix: ImportErrors

After you've installed Pandas, you should check to see if it was successful. You might test it by importing pandas into your application. However, you may occasionally obtain a "no module called 'pandas'" error, which is fairly common. This error arises when Python does not recognize the pandas library in your existing environment. This section will look at numerous approaches to address this issue.

This issue might occur if you have numerous Python installations on your machine and need pandas installed on the Python installation you are currently using. Type which python into your terminal in Linux or Mac OS to discover which Python installation or version you're running. If it's anything like "/usr/bin/python" , you're using the system Python, which isn't advised.

Conda is highly recommended for rapid installation and package and dependency updates. You may use the methods mentioned previously in the text to install pandas using conda.

How to Fix : NameError

Another typical error message while using Pandas is NameError: name 'pd' is not defined. This problem commonly happens when we import the Python library pandas but forget to give it the alias pd. The examples below show how this problem arises in practice and how to correct it quickly.

Code:

Output:

We imported pandas but did not assign it the alias pd. As a result, an error was generated. We may either replace all of the pd's in the preceding code with pandas or provide an alias pd to pandas when importing it. For a better understanding, consider the following code:

Code:

Output:

Code:

Output:

This gets us to the conclusion of the article. Kudos :tada: ! You have now successfully installed the Pandas library on your machine and will be able to resolve a few of the frequent installation errors if any one of them arises.

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.

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 dependency section.

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.

Установка¶

Проще всего установить 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.

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 dependency section.

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.

Введение в библиотеку pandas: установка и первые шаги / pd 1

Библиотека pandas в Python — это идеальный инструмент для тех, кто занимается анализом данных, используя для этого язык программирования Python.

В этом материале речь сначала пойдет об основных аспектах библиотеки и о том, как установить ее в систему. Потом вы познакомитесь с двумя структурам данных: series и dataframes . Сможете поработать с базовым набором функций, предоставленных библиотекой pandas, для выполнения основных операций по обработке. Знакомство с ними — ключевой навык для специалиста в этой сфере. Поэтому так важно перечитать материал до тех, пока он не станет понятен на 100%.

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

Библиотека Python для анализа данных

Pandas — это библиотека Python с открытым исходным кодом для специализированного анализа данных. Сегодня все, кто использует Python для изучения статистических целей анализа и принятия решений, должны быть с ней знакомы.

Библиотека была спроектирована и разработана преимущественно Уэсом Маккини в 2008 году. В 2012 к нему присоединился коллега Чан Шэ. Вместе они создали одну из самых используемых библиотек в сообществе Python.

Pandas появилась из необходимости в простом инструменте для обработки, извлечения и управления данными.

Этот пакет Python спроектирован на основе библиотеки NumPy. Такой выбор обуславливает успех и быстрое распространение pandas. Он также пользуется всеми преимуществами NumPy и делает pandas совместимой с большинством другим модулей.

Еще одно важное решение — разработка специальных структур для анализа данных. Вместо того, чтобы использовать встроенные в Python или предоставляемые другими библиотеками структуры, были разработаны две новых.

Они спроектированы для работы с реляционными и классифицированными данными, что позволяет управлять данными способом, похожим на тот, что используется в реляционных базах SQL и таблицах Excel.

Дальше вы встретите примеры базовых операций для анализа данных, которые обычно используются на реляционных или таблицах Excel. Pandas предоставляет даже более расширенный набор функций и методов, позволяющих выполнять эти операции эффективнее.

Основная задача pandas — предоставить все строительные блоки для всех, кто погружается в мир анализа данных.

Установка pandas

Простейший способ установки библиотеки pandas — использование собранного решения, то есть установка через Anaconda или Enthought.

Установка в Anaconda

В Anaconda установка занимает пару минут. В первую очередь нужно проверить, не установлен ли уже pandas, и если да, то какая это версия. Для этого введите следующую команду в терминале:

Если модуль уже установлен (например в Windows), вы получите приблизительно следующий результат:

Если pandas не установлена, ее необходимо установить. Введите следующую команду:

Anaconda тут же проверит все зависимости и установит дополнительные модули.

Если требуется обновить пакет до более новой версии, используется эта интуитивная команда:

Система проверит версию pandas и версию всех модулей, а затем предложит соответствующие обновления. Затем предложит перейти к обновлению.

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

Pandas можно установить и с помощью PyPI, используя эту команду:

Установка в Linux

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

В Debian и Ubuntu используется команда:

А для OpenSuse и Fedora — эта:

Установка из источника

Если есть желание скомпилировать модуль pandas из исходного кода, тогда его можно найти на GitHub по ссылке https://github.com/pandas-dev/pandas:

Убедитесь, что Cython установлен. Больше об этом способе можно прочесть в документации: (http://pandas.pydata.org/pandas-docs/stable/install.html).

Репозиторий для Windows

Если вы работаете в Windows и предпочитаете управлять пакетами так, чтобы всегда была установлена последняя версия, то существует ресурс, где всегда можно загрузить модули для Windows: Christoph Gohlke’s Python Extension Packages for Windows (www.lfd.uci.edu/

gohlke/pythonlibs/). Каждый модуль поставляется в формате WHL для 32 и 64-битных систем. Для установки нужно использовать приложение pip:

Например, для установки pandas потребуется найти и загрузить следующий пакет:

При выборе модуля важно выбрать нужную версию Python и архитектуру. Более того, если для NumPy пакеты не требуются, то у pandas есть зависимости. Их также необходимо установить. Порядок установки не имеет значения.

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

Проверка установки pandas

Библиотека pandas может запустить проверку после установки для верификации управляющих элементов (документация утверждает, что тест покрывает 97% всего кода).

Во-первых, нужно убедиться, что установлен модуль nose . Если он имеется, то тестирование проводится с помощью следующей команды:

Оно займет несколько минут и в конце покажет список проблем.

Модуль Nose

Этот модуль спроектирован для проверки кода Python во время этапов разработки проекта или модуля Python. Он расширяет возможности модуль unittest . Nose используется для проверки кода и упрощает процесс.

Здесь о нем можно почитать подробнее: _http://pythontesting.net/framework/nose/nose-introduction/.

Первые шаги с pandas

Лучший способ начать знакомство с pandas — открыть консоль Python и вводить команды одна за одной. Таким образом вы познакомитесь со всеми функциями и структурами данных.

Более того, данные и функции, определенные здесь, будут работать и в примерах будущих материалов. Однако в конце каждого примера вы вольны экспериментировать с ними.

Для начала откройте терминал Python и импортируйте библиотеку pandas. Стандартная практика для импорта модуля pandas следующая:

Теперь, каждый раз встречая pd и np вы будете ссылаться на объект или метод, связанный с этими двумя библиотеками, хотя часто будет возникать желание импортировать модуль таким образом:

В таком случае ссылаться на функцию, объект или метод с помощью pd уже не нужно, а это считается не очень хорошей практикой в среде разработчиков Python.

How to Install Pandas in Python?

When analyzing data using Python, Pandas is a game changer, one of the most popular and commonly used tools in data analytics. What's nice about Pandas is that it takes data from a CSV or TSV file or a SQL database and generates a Python object with rows and columns called a data frame, which looks remarkably similar to a table in statistics tools like Excel. Working with this is far more convenient than dealing with lists and/or dictionaries. However, to work with it, we must first learn how to install Pandas on our system and then install Pandas on our devices.

Introduction

NumPy may considerably simplify our lives when dealing with large amounts of numerical data. However, there are occasions when various data are involved, and Numpy is not usually the ideal choice. Pandas come in helpful in such cases. It has numerous application possibilities, but the preferable situation is to read files that are not solely numerical, such as " .csv " or " .xlsx " files which include numerical data and textual metadata about those data.

Before delving into the intricacies of the Pandas Library, we must first grasp the idea of NumPy arrays. But why NumPy? Because NumPy is the foundation of the open-source software package Pandas.

Now that you're familiar with NumPy let's move on to Pandas.

Introduction to Pandas

So, what exactly is Pandas? Pandas is an acronym that stands for " Python Data Analysis Library." Pandas is a widely used library for managing tabular data, data manipulation, and analysis based on NumPy. The fact that Pandas saves the information as a Python object containing rows and columns, comparable to data saved in Excel files, is probably its best feature. Also, we can quickly view our data in this manner, which makes our task much easier than dealing with data in the form of lists or dictionaries. Also, it has an advantage over NumPy in that it can handle numerous data types (e.g., strings), rather than only numerical data; nonetheless, this makes it slower than NumPy.

Following a quick introduction to Pandas, let us look at the prerequisites before installing Pandas on our system.

Prerequisites

To "work with" Pandas, we must first install it. Python 3.5.x or later is also required. It requires Python 3.6, 3.7, or 3.8 as a prerequisite for installation. It also relies on other libraries (such as NumPy) and has optional dependencies (like Matplotlib for plotting). As a result, the simplest approach to get Pandas up and running is to use PyPi or Conda to install it. Conda is the package manager upon which the Anaconda distribution is based. It is a cross-platform and language-independent package manager.

Now let us look at how we can install Pandas on our system. Before installing the Pandas package, ensure that you have installed Python or Anaconda and have established the environment variables to access Python, pip, or pip3 commands through the command line, shell, or terminal according to your operating system.

Install Pandas on Windows

As previously said, we can update or get Pandas to the newest version in various methods based on how we installed Python. First, let's look at installing Pandas on Windows using the pip and conda commands.

Method 1: Using pip

It's a package installation tool that simplifies the installation of Python modules and frameworks. Pip will be installed with Python by default if you have a later version of Python available (greater than Python 3.5.x). If you're using an earlier version of Python, you'll need to install pip before you can install Pandas. The simplest method to accomplish this is to update to the most recent version of Python, which can be found at this link.

Step 1: Launch Command Prompt

To open the start menu, use the Windows key on your keyboard or click the Start button. For example, when you type "cmd" the Command Prompt app should display in the start menu, and once you can view the command prompt app, launch the app. Alternatively, you may hit the Windows key + r to bring up the "RUN" box, where you can input “cmd” and then press enter. It will also launch the Command prompt.

Step 2: Enter the command

After you open the command prompt, the following step is to enter the needed command to begin the pip installation. For example, enter the command shown below.

This will start the pip installation. After downloading the necessary files, Pandas will be set to operate on your computer. You can employ Pandas in your Python projects once the installation has been completed.

Method 2: Using conda

Installing Pandas using Anaconda is the best option if you are unfamiliar with command-line programming. Anaconda is a sophisticated Python distribution that provides access to various libraries besides Pandas. Anaconda will become increasingly handy as you learn further about Python.

Step 1 : Download Anaconda

To install Anaconda, go to this page and then click on the "Download" button on the right.

The file of the latest version of Python available for your Windows PC will start downloading.

Step 2 : Install Anaconda

Start your installation from the website by clicking the "Next" button.

Then, click the "I Agree" option to accept the licensing agreement.

Then, pick the user accounts for whom Pandas should be installed. We proceeded by selecting the recommended "Just Me" option.

In the wizard's concluding stage, you must specify where the distribution will be downloaded.

Finally, under the advanced installation options area, tick the "Add Anaconda to my PATH environment variable" and "Register Anaconda3 as my preferred Python 3.x (x over here denotes whatever the current version could be)" choices.

The installation of Anaconda will begin when you click the "Install" button. When the setup is finished, you will see the "Installation Complete" screen within a few minutes. It appears as follows:

The Pandas libraries on your Windows system will all be available now. This is due to the fact Anaconda automatically downloads all of the key libraries during installation.

Install Pandas on Linux

Depending on the package management of your Linux distribution, there are three ways to install pandas. We can either :

  1. install it with pip,
  2. install it with conda, or
  3. download it from the package manager's repository.

Installing pandas through the distribution's package manager's repository is untrustworthy since the repository frequently contains an earlier version of pandas. Furthermore, Conda will require you to set it up before installing pandas, which will lengthen the procedure. As a result, installing Pandas using pip is the ideal option since it installs the most recent version and eliminates the need to go through multiple steps to set up another required tool.

For Ubuntu Users

Method 1 : Using Pip

This method is quite identical to the one described in the section "Install Pandas on Windows."

  • Step 1: Install pip

Running the following line in your terminal will install pip3 on your Linux system:

Remember that because pip requires Python 3, Python 3 must be downloaded on your Linux system. When you execute the command, you may see something like this:

The program will also download " python-pip-whl " and " python3-wheel, " as you can see. The "Wheel" package format is integrated into Python.

To begin the installation process, type the " Y " key. When the procedure is finished, you can go to the next stage.

  • Step 2 : Install Pandas

Now that pip is installed on your Linux system, and you can use it to install Pandas. You only need to execute the following command in the terminal:

When the command completes, Pandas will be installed on your Linux system.

Method 2: Using Anaconda

If Anaconda is pre-installed on your Linux computer, proceed to step 2. For example, to download Anaconda on Ubuntu 20.04, follow the following step:

  • Step 1 : Install Anaconda

To begin installing Anaconda, you first must install the necessary installer. To do so, go to this website and scroll a little. To the right of the website is a section labeled "Get Additional Installers." Select the Linux icon.

Scroll to the "Anaconda Installers" portion of the website. Locate the installation for your Linux system and right-click on it. Then, select the "Copy link address" option.

You must use "wget" to install the script now that you have copied the URL to the bash installer with the ".sh" suffix to your clipboard.

Launch your terminal and browse to your home directory using the cd command. Next, make a directory called "temporary" following. Then, go to the newly formed temporary folder and use the "wget" command as described below to install the installation.

The script is huge, so you'll have to wait a while to install it.

After downloading the script, you must run it to set up Anaconda3 on your system. Make sure you're in the temporary directory before running any commands. After that, execute the following command:

The licensing agreement will be shown, and you must approve it to install Anaconda. Then, you must allow Anaconda to be added to your machine's PATH variable. Anaconda will be invoked anytime you put " $ python " in your terminal after being added to your machine's PATH.

For Fedora Users

Fedora users can acquire the newest version of Pandas by running the following command in their system's terminal.

Using your Linux distribution's package manager to install Pandas

Python Pandas library can be installed in various methods, although Linux distributions such as Ubuntu, Debian, CentOS/RHEL, Fedora, OpenSuse, and others include the pandas package in their official repositories. The pandas package may be installed using the apt, yum, or dnf package managers. Please see the following table for a better understanding:

Sr No. Distribution Official Link Bash Command
1 Debian Official Debian Repository Link sudo apt-get install python3-pandas
2 Ubuntu Official Ubuntu Repository Link sudo apt-get install python3-pandas
3 OpenSuse Official OpenSuse Repository Link zypper in python3-pandas
4 Centos/RHEL Official EPEL Repository Link yum install python3-pandas
5 Fedora Official Fedora Repository Link dnf install python3-pandas

Install Pandas on Mac OS

You may install pandas on Mac OS using pip or conda as you did on Windows or Linux.

Method 1 : Using pip

Assuming you installed pip successfully on our Mac OS device. Once pip is installed on your device, run the following command in your terminal to install Pandas.

If you're not the root user, sudo may not function well because sudo downloads Python packages in the root directory, where you might need access to write files. If you wish to download to a specific user, use the "—user" option.

Vola! Now Pandas have been installed on your device.

Advanced Usage

Using Anaconda

Installing pandas and the rest of the NumPy and SciPy stack might be challenging for novice users. However, anaconda, a cross-platform (Linux, macOS, Windows) Python distribution for data analytics and scientific computing, is the simplest method to install not just pandas but also Python and the most popular programs comprising the SciPy stack (IPython, NumPy, Matplotlib. ). After executing the installer, the user will have access to pandas and the rest of the SciPy stack without installing or waiting for any software to be constructed.

To get a clear image of how to download Anaconda for your system, follow the instructions outlined in the article earlier based on your operating system.

Using Miniconda

In the preceding sections, we described how to install pandas as a package of the Anaconda distribution. However, that method requires installing well over a hundred libraries and installing the installer, which is a few hundred mbs in size.

If you want greater control over whatever library you wish to install or have restricted internet speed, installing pandas using Miniconda may be preferable.

You may obtain your miniconda installation from the following Link. You can select the operating system and version that you want to install. You now have conda setup on your device after installing miniconda, which means you may install Pandas with the following command:

Using PyPi

Pandas may be installed via PyPI using pip. Run the following command in your terminal or command line to install pandas on your device.

Using ActivePython

ActivePython , like Anaconda, is a powerful Python distribution that, in addition to Pandas, gives access to a large range of libraries. This implies that after we install ActivePython, the pandas library will be downloaded automatically as part of the ActivePython installation. You may browse to the following website, search for your operating system, and then follow the procedures to get the current version of Python as well as the Pandas package on your system.

Installing directly from the source

The Pandas library's source code is available at this link, and it may be downloaded from there by following the methods outlined below:

Downloading from the git repository necessitates a current Cython installation. So, first, you should download the MinGW compiler suite on Windows. Once the property has been configured, perform the following commands from the command line:

It should be noted that if you launch an interpreter in the source directory, you will be unable to import pandas until you construct the C extensions in place using the command line as follow:

Obtaining the newest version of Pandas using the pip or conda command rather than installing straight from the source as it lengthens the process.

How to fix: ImportErrors

After you've installed Pandas, you should check to see if it was successful. You might test it by importing pandas into your application. However, you may occasionally obtain a "no module called 'pandas'" error, which is fairly common. This error arises when Python does not recognize the pandas library in your existing environment. This section will look at numerous approaches to address this issue.

This issue might occur if you have numerous Python installations on your machine and need pandas installed on the Python installation you are currently using. Type which python into your terminal in Linux or Mac OS to discover which Python installation or version you're running. If it's anything like "/usr/bin/python" , you're using the system Python, which isn't advised.

Conda is highly recommended for rapid installation and package and dependency updates. You may use the methods mentioned previously in the text to install pandas using conda.

How to Fix : NameError

Another typical error message while using Pandas is NameError: name 'pd' is not defined. This problem commonly happens when we import the Python library pandas but forget to give it the alias pd. The examples below show how this problem arises in practice and how to correct it quickly.

Code:

Output:

We imported pandas but did not assign it the alias pd. As a result, an error was generated. We may either replace all of the pd's in the preceding code with pandas or provide an alias pd to pandas when importing it. For a better understanding, consider the following code:

Code:

Output:

Code:

Output:

This gets us to the conclusion of the article. Kudos :tada: ! You have now successfully installed the Pandas library on your machine and will be able to resolve a few of the frequent installation errors if any one of them arises.

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

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