Как импортировать pandas в python
Перейти к содержимому

Как импортировать pandas в python

  • автор:

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.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 using your Linux distribution’s package manager.#

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

Библиотека 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.

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

Pandas (in addition to Numpy) is the go-to Python library for all your data science needs. It helps with dealing with input data in CSV formats and with transforming your data into a form where it can be inputted into ML models.

How to install Pandas?

To install Python Pandas, go to your command line/ terminal and type “pip install pandas” or else, if you have anaconda installed in your system, just type in “conda install pandas”. Once the installation is completed, go to your IDE (Jupyter, PyCharm etc.) and simply import it by typing: “import pandas as pd”

Python Pandas Operations

Using Python pandas, you can perform a lot of operations with series, data frames, missing data, group by etc. Some of the common operations for data manipulation are listed below:

Loading in Data

The first step in any ML problem is identifying what format your data is in, and then loading it into whatever framework you’re using. For Kaggle competitions, a lot of data can be found in CSV files, so that’s the example we’re going to use.

Just think of it as a table for now.

The Basics

Now that we have our data frame in our variable df, let’s look at what it contains. We can use the function head() to see the first couple rows of the data frame (or the function tail() to see the last few rows).

We can see the dimensions of the data frame using the shape attribute

We can also extract all the column names as a list, by using the columns attribute and can extract the rows with the index attribute

In order to get a better idea of the type of data that we are dealing with, we can call the describe() function to see statistics like mean, min, etc about each column of the dataset.

Okay, so now let’s looking at information that we want to extract from the data frame. Let’s say I wanted to know the max value of a certain column. The function max() will show you the maximum values of all columns

Then, if you’d like to specifically get the max value for a particular column, you pass in the name of the column using the bracket indexing operator

If you’d like to find the mean of the Losing teams’ score.

But what if that’s not enough? Let’s say we want to actually see the game(row) where this max score happened. We can call the argmax() function to identify the row index

One of the most useful functions that you can call on certain columns in a data frame is the value_counts() function. It shows how many times each item appears in the column. This particular command shows the number of games in each season

Notice the slight difference in that iloc is exclusive of the second number, while loc is inclusive.

Below is an example of how you can use loc to achieve the same task as we did previously with iloc

A faster version uses the at() function. At() is really useful whenever you know the row label and the column label of the particular value that you want to get.

If you’d like to see more discussion on how loc and iloc are different, check out this great Stack Overflow post: http://stackoverflow.com/questions/31593201/pandas-iloc-vs-ix-vs-loc-explanation. Just remember that iloc looks at position and loc looks at labels. Loc becomes very important when your row labels aren’t integers.

Sorting

Let’s say that we want to sort the data frame in increasing order for the scores of the losing team

Filtering Rows Conditionally

Now, let’s say we want to find all of the rows that satisfy a particular condition. For example, I want to find all of the games where the winning team scored more than 150 points. The idea behind this command is you want to access the column ‘Wscore’ of the data frame df (df[‘Wscore’]), find which entries are above 150 (df[‘Wscore’] > 150), and then returns only those specific rows in a data frame format (df[df[‘Wscore’] > 150]).

This also works if you have multiple conditions. Let’s say we want to find out when the winning team scores more than 150 points and when the losing team scores below 100.

Grouping

Another important function in Pandas is groupby(). This is a function that allows you to group entries by certain attributes (e.g Grouping entries by Wteam number) and then perform operations on them. The following function groups all the entries (games) with the same Wteam number and finds the mean for each group.

This next command groups all the games with the same Wteam number and finds where how many times that specific team won at home, on the road, or at a neutral site

Each data frame has a values attribute which is useful because it basically displays your data frame in a numpy array style format

Now, you can simply just access elements like you would in an array.

Extracting Rows and Columns

The bracket indexing operator is one way to extract certain columns from a data frame.

Notice that you can achieve the same result by using the loc function. Loc is a very versatile function that can help you in a lot of accessing and extracting tasks.

Note the difference is the return types when you use brackets and when you use double brackets.

You’ve seen before that you can access columns through df[‘col name’]. You can access rows by using slicing operations.

Here’s an equivalent using iloc

Data Cleaning

One of the big jobs of doing well in Kaggle competitions is that of data cleaning. A lot of times, the CSV file you’re given (especially like in the Titanic dataset), you’ll have a lot of missing values in the dataset, which you have to identify. The following isnull function will figure out if there are any missing values in the data frame, and will then sum up the total for each column. In this case, we have a pretty clean dataset.

If you do end up having missing values in your datasets, be sure to get familiar with these two functions.

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

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