Series python что это
pandas.SeriesВ¶
One-dimensional ndarray with axis labels (including time series).
Labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Statistical methods from ndarray have been overridden to automatically exclude missing data (currently represented as NaN).
Parameters data array-like, Iterable, dict, or scalar value
Contains data stored in Series. If data is a dict, argument order is maintained.
index array-like or Index (1d)
dtype str, numpy.dtype, or ExtensionDtype, optional
name str, optional
The name to give to the Series.
copy bool, default False
Copy input data. Only affects Series or 1d ndarray input. See examples.
Constructing Series from a dictionary with an Index specified
The keys of the dictionary match with the Index values, hence the Index values have no effect.
Note that the Index is first build with the keys from the dictionary. After this the Series is reindexed with the given Index values, hence we get all NaN as a result.
Due to input data type the Series has a view on the original data, so the data is changed as well.
Return the transpose, which is by definition self.
The ExtensionArray of the data backing this Series or Index.
Access a single value for a row/column label pair.
Dictionary of global attributes of this dataset.
Return a list of the row axis labels.
Return the dtype object of the underlying data.
Return the dtype object of the underlying data.
Get the properties associated with this pandas object.
Return if I have any nans; enables various perf speedups.
Access a single value for a row/column pair by integer position.
Purely integer-location based indexing for selection by position.
The index (axis labels) of the Series.
Return boolean if values in the object are monotonic_increasing.
Return boolean if values in the object are monotonic_decreasing.
Alias for is_monotonic.
Return boolean if values in the object are unique.
Access a group of rows and columns by label(s) or a boolean array.
Return the name of the Series.
Return the number of bytes in the underlying data.
Number of dimensions of the underlying data, by definition 1.
Return a tuple of the shape of the underlying data.
Return the number of elements in the underlying data.
Return Series as ndarray or ndarray-like depending on the dtype.
empty
Return a Series/DataFrame with absolute numeric value of each element.
add (other[,В level,В fill_value,В axis])
Return Addition of series and other, element-wise (binary operator add ).
Aggregate using one or more operations over the specified axis.
Aggregate using one or more operations over the specified axis.
Align two objects on their axes with the specified join method.
all ([axis,В bool_only,В skipna,В level])
Return whether all elements are True, potentially over an axis.
any ([axis,В bool_only,В skipna,В level])
Return whether any element is True, potentially over an axis.
Concatenate two or more Series.
apply (func[,В convert_dtype,В args])
Invoke function on values of Series.
Return int position of the largest value in the Series.
Return int position of the smallest value in the Series.
Return the integer indices that would sort the Series values.
Convert time series to specified frequency.
astype (dtype[,В copy,В errors])
Select values at particular time of day (e.g., 9:30AM).
Compute the lag-N autocorrelation.
backfill ([axis,В inplace,В limit,В downcast])
between (left,В right[,В inclusive])
Select values between particular times of the day (e.g., 9:00-9:30 AM).
bfill ([axis,В inplace,В limit,В downcast])
Return the bool of a single element Series or DataFrame.
alias of pandas.core.arrays.categorical.CategoricalAccessor
clip ([lower,В upper,В axis,В inplace])
Trim values at input threshold(s).
combine (other,В func[,В fill_value])
Update null elements with value in the same location in ‘other’.
Compare to another Series and show the differences.
Make a copy of this object’s indices and data.
corr (other[,В method,В min_periods])
Compute correlation with other Series, excluding missing values.
Return number of non-NA/null observations in the Series.
cov (other[,В min_periods,В ddof])
Compute covariance with Series, excluding missing values.
Return cumulative maximum over a DataFrame or Series axis.
Return cumulative minimum over a DataFrame or Series axis.
Return cumulative product over a DataFrame or Series axis.
Return cumulative sum over a DataFrame or Series axis.
Generate descriptive statistics.
First discrete difference of element.
div (other[,В level,В fill_value,В axis])
Return Floating division of series and other, element-wise (binary operator truediv ).
divide (other[,В level,В fill_value,В axis])
Return Floating division of series and other, element-wise (binary operator truediv ).
divmod (other[,В level,В fill_value,В axis])
Return Integer division and modulo of series and other, element-wise (binary operator divmod ).
Compute the dot product between the Series and the columns of other.
Return Series with specified index labels removed.
Return Series with duplicate values removed.
Return Series/DataFrame with requested index / column level(s) removed.
dropna ([axis,В inplace,В how])
Return a new Series with missing values removed.
alias of pandas.core.indexes.accessors.CombinedDatetimelikeProperties
Indicate duplicate Series values.
eq (other[,В level,В fill_value,В axis])
Return Equal to of series and other, element-wise (binary operator eq ).
Test whether two objects contain the same elements.
Provide exponential weighted (EW) functions.
expanding ([min_periods,В center,В axis,В method])
Provide expanding transformations.
Transform each element of a list-like to a row.
Encode the object as an enumerated type or categorical variable.
ffill ([axis,В inplace,В limit,В downcast])
Fill NA/NaN values using the specified method.
filter ([items,В like,В regex,В axis])
Subset the dataframe rows or columns according to the specified index labels.
Select initial periods of time series data based on a date offset.
Return index for first non-NA value or None, if no NA value is found.
floordiv (other[,В level,В fill_value,В axis])
Return Integer division of series and other, element-wise (binary operator floordiv ).
ge (other[,В level,В fill_value,В axis])
Return Greater than or equal to of series and other, element-wise (binary operator ge ).
Get item from object for given key (ex: DataFrame column).
Group Series using a mapper or by a Series of columns.
gt (other[,В level,В fill_value,В axis])
Return Greater than of series and other, element-wise (binary operator gt ).
Return the first n rows.
Draw histogram of the input series using matplotlib.
Return the row label of the maximum value.
Return the row label of the minimum value.
Attempt to infer better dtypes for object columns.
Fill NaN values using an interpolation method.
Detect missing values.
Detect missing values.
Return the first element of the underlying data as a Python scalar.
Lazily iterate over (index, value) tuples.
Lazily iterate over (index, value) tuples.
Return alias for index.
kurt ([axis,В skipna,В level,В numeric_only])
Return unbiased kurtosis over requested axis.
kurtosis ([axis,В skipna,В level,В numeric_only])
Return unbiased kurtosis over requested axis.
Select final periods of time series data based on a date offset.
Return index for last non-NA value or None, if no NA value is found.
le (other[,В level,В fill_value,В axis])
Return Less than or equal to of series and other, element-wise (binary operator le ).
lt (other[,В level,В fill_value,В axis])
Return Less than of series and other, element-wise (binary operator lt ).
mad ([axis,В skipna,В level])
Return the mean absolute deviation of the values over the requested axis.
Map values of Series according to input correspondence.
Replace values where the condition is True.
max ([axis,В skipna,В level,В numeric_only])
Return the maximum of the values over the requested axis.
mean ([axis,В skipna,В level,В numeric_only])
Return the mean of the values over the requested axis.
median ([axis,В skipna,В level,В numeric_only])
Return the median of the values over the requested axis.
Return the memory usage of the Series.
min ([axis,В skipna,В level,В numeric_only])
Return the minimum of the values over the requested axis.
mod (other[,В level,В fill_value,В axis])
Return Modulo of series and other, element-wise (binary operator mod ).
Return the mode(s) of the Series.
mul (other[,В level,В fill_value,В axis])
Return Multiplication of series and other, element-wise (binary operator mul ).
multiply (other[,В level,В fill_value,В axis])
Return Multiplication of series and other, element-wise (binary operator mul ).
ne (other[,В level,В fill_value,В axis])
Return Not equal to of series and other, element-wise (binary operator ne ).
Return the largest n elements.
Detect existing (non-missing) values.
Detect existing (non-missing) values.
Return the smallest n elements.
Return number of unique elements in the object.
pad ([axis,В inplace,В limit,В downcast])
pct_change ([periods,В fill_method,В limit,В freq])
Percentage change between the current and a prior element.
pipe (func,В *args,В **kwargs)
Apply func(self, *args, **kwargs).
alias of pandas.plotting._core.PlotAccessor
Return item and drops from series.
pow (other[,В level,В fill_value,В axis])
Return Exponential power of series and other, element-wise (binary operator pow ).
Return the product of the values over the requested axis.
Return the product of the values over the requested axis.
Return value at the given quantile.
radd (other[,В level,В fill_value,В axis])
Return Addition of series and other, element-wise (binary operator radd ).
Compute numerical data ranks (1 through n) along axis.
Return the flattened underlying data as an ndarray.
rdiv (other[,В level,В fill_value,В axis])
Return Floating division of series and other, element-wise (binary operator rtruediv ).
rdivmod (other[,В level,В fill_value,В axis])
Return Integer division and modulo of series and other, element-wise (binary operator rdivmod ).
Conform Series to new index with optional filling logic.
Return an object with matching indices as other object.
Alter Series index labels or name.
Set the name of the axis for the index or columns.
Rearrange index levels using input order.
Repeat elements of a Series.
Resample time-series data.
reset_index ([level,В drop,В name,В inplace])
Generate a new DataFrame or Series with the index reset.
rfloordiv (other[,В level,В fill_value,В axis])
Return Integer division of series and other, element-wise (binary operator rfloordiv ).
rmod (other[,В level,В fill_value,В axis])
Return Modulo of series and other, element-wise (binary operator rmod ).
rmul (other[,В level,В fill_value,В axis])
Return Multiplication of series and other, element-wise (binary operator rmul ).
Provide rolling window calculations.
Round each value in a Series to the given number of decimals.
rpow (other[,В level,В fill_value,В axis])
Return Exponential power of series and other, element-wise (binary operator rpow ).
rsub (other[,В level,В fill_value,В axis])
Return Subtraction of series and other, element-wise (binary operator rsub ).
rtruediv (other[,В level,В fill_value,В axis])
Return Floating division of series and other, element-wise (binary operator rtruediv ).
Return a random sample of items from an axis of object.
Find indices where elements should be inserted to maintain order.
sem ([axis,В skipna,В level,В ddof,В numeric_only])
Return unbiased standard error of the mean over requested axis.
set_axis (labels[,В axis,В inplace])
Assign desired index to given axis.
set_flags (*[,В copy,В allows_duplicate_labels])
Return a new object with updated flags.
shift ([periods,В freq,В axis,В fill_value])
skew ([axis,В skipna,В level,В numeric_only])
Return unbiased skew over requested axis.
(DEPRECATED) Equivalent to shift without copying data.
Sort Series by index labels.
Sort by the values.
alias of pandas.core.arrays.sparse.accessor.SparseAccessor
Squeeze 1 dimensional axis objects into scalars.
std ([axis,В skipna,В level,В ddof,В numeric_only])
Return sample standard deviation over requested axis.
alias of pandas.core.strings.accessor.StringMethods
sub (other[,В level,В fill_value,В axis])
Return Subtraction of series and other, element-wise (binary operator sub ).
subtract (other[,В level,В fill_value,В axis])
Return Subtraction of series and other, element-wise (binary operator sub ).
Return the sum of the values over the requested axis.
Interchange axes and swap values axes appropriately.
Return the last n rows.
take (indices[,В axis,В is_copy])
Return the elements in the given positional indices along an axis.
Copy object to the system clipboard.
Write object to a comma-separated values (csv) file.
Write object to an Excel sheet.
Convert Series to DataFrame.
Write the contained data to an HDF5 file using HDFStore.
Convert the object to a JSON string.
Render object to a LaTeX tabular, longtable, or nested table/tabular.
Return a list of the values.
to_markdown ([buf,В mode,В index,В storage_options])
Print Series in Markdown-friendly format.
to_numpy ([dtype,В copy,В na_value])
A NumPy ndarray representing the values in this Series or Index.
Convert Series from DatetimeIndex to PeriodIndex.
Pickle (serialize) object to file.
Write records stored in a DataFrame to a SQL database.
Render a string representation of the Series.
Cast to DatetimeIndex of Timestamps, at beginning of period.
Return an xarray object from the pandas object.
Return a list of the values.
Call func on self producing a Series with transformed values.
Return the transpose, which is by definition self.
truediv (other[,В level,В fill_value,В axis])
Return Floating division of series and other, element-wise (binary operator truediv ).
truncate ([before,В after,В axis,В copy])
Truncate a Series or DataFrame before and after some index value.
tshift ([periods,В freq,В axis])
(DEPRECATED) Shift the time index, using the index’s frequency if available.
tz_convert (tz[,В axis,В level,В copy])
Convert tz-aware axis to target time zone.
Localize tz-naive index of a Series or DataFrame to target time zone.
Return unique values of Series object.
Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.
Modify Series in place using values from passed Series.
Return a Series containing counts of unique values.
var ([axis,В skipna,В level,В ddof,В numeric_only])
Return unbiased variance over requested axis.
Create a new view of the Series.
Replace values where the condition is False.
xs (key[,В axis,В level,В drop_level])
Return cross-section from the Series/DataFrame.
Введение в pandas: анализ данных на Python
pandas это высокоуровневая Python библиотека для анализа данных. Почему я её называю высокоуровневой, потому что построена она поверх более низкоуровневой библиотеки NumPy (написана на Си), что является большим плюсом в производительности. В экосистеме Python, pandas является наиболее продвинутой и быстроразвивающейся библиотекой для обработки и анализа данных. В своей работе мне приходится пользоваться ею практически каждый день, поэтому я пишу эту краткую заметку для того, чтобы в будущем ссылаться к ней, если вдруг что-то забуду. Также надеюсь, что читателям блога заметка поможет в решении их собственных задач с помощью pandas, и послужит небольшим введением в возможности этой библиотеки.
DataFrame и Series
Чтобы эффективно работать с pandas, необходимо освоить самые главные структуры данных библиотеки: DataFrame и Series. Без понимания что они из себя представляют, невозможно в дальнейшем проводить качественный анализ.
Series
Структура/объект Series представляет из себя объект, похожий на одномерный массив (питоновский список, например), но отличительной его чертой является наличие ассоциированных меток, т.н. индексов, вдоль каждого элемента из списка. Такая особенность превращает его в ассоциативный массив или словарь в Python.
В строковом представлении объекта Series, индекс находится слева, а сам элемент справа. Если индекс явно не задан, то pandas автоматически создаёт RangeIndex от 0 до N-1, где N общее количество элементов. Также стоит обратить, что у Series есть тип хранимых элементов, в нашем случае это int64, т.к. мы передали целочисленные значения.
У объекта Series есть атрибуты через которые можно получить список элементов и индексы, это values и index соответственно.
Доступ к элементам объекта Series возможны по их индексу (вспоминается аналогия со словарем и доступом по ключу).
Индексы можно задавать явно:
Делать выборку по нескольким индексам и осуществлять групповое присваивание:
Фильтровать Series как душе заблагорассудится, а также применять математические операции и многое другое:
Если Series напоминает нам словарь, где ключом является индекс, а значением сам элемент, то можно сделать так:
У объекта Series и его индекса есть атрибут name, задающий имя объекту и индексу соответственно.
Индекс можно поменять «на лету», присвоив список атрибуту index объекта Series
Имейте в виду, что список с индексами по длине должен совпадать с количеством элементов в Series.
DataFrame
Объект DataFrame лучше всего представлять себе в виде обычной таблицы и это правильно, ведь DataFrame является табличной структурой данных. В любой таблице всегда присутствуют строки и столбцы. Столбцами в объекте DataFrame выступают объекты Series, строки которых являются их непосредственными элементами.
DataFrame проще всего сконструировать на примере питоновского словаря:
Чтобы убедиться, что столбец в DataFrame это Series, извлекаем любой:
Объект DataFrame имеет 2 индекса: по строкам и по столбцам. Если индекс по строкам явно не задан (например, колонка по которой нужно их строить), то pandas задаёт целочисленный индекс RangeIndex от 0 до N-1, где N это количество строк в таблице.
В таблице у нас 4 элемента от 0 до 3.
Доступ по индексу в DataFrame
Индекс по строкам можно задать разными способами, например, при формировании самого объекта DataFrame или «на лету»:
Доступ к строкам по индексу возможен несколькими способами:
Можно делать выборку по индексу и интересующим колонкам:
Фильтровать DataFrame с помощью т.н. булевых массивов:
Кстати, к столбцам можно обращаться, используя атрибут или нотацию словарей Python, т.е. df.population и df[‘population’] это одно и то же.
Сбросить индексы можно вот так:
pandas при операциях над DataFrame, возвращает новый объект DataFrame.
Добавим новый столбец, в котором население (в миллионах) поделим на площадь страны, получив тем самым плотность:
Не нравится новый столбец? Не проблема, удалим его:
Особо ленивые могут просто написать del df[‘density’].
Переименовывать столбцы нужно через метод rename:
В этом примере перед тем как переименовать столбец Country Code, убедитесь, что с него сброшен индекс, иначе не будет никакого эффекта.
Чтение и запись данных
pandas поддерживает все самые популярные форматы хранения данных: csv, excel, sql, буфер обмена, html и многое другое:
Чаще всего приходится работать с csv-файлами. Например, чтобы сохранить наш DataFrame со странами, достаточно написать:
Функции to_csv ещё передаются различные аргументы (например, символ разделителя между колонками) о которых подробнее можно узнать в официальной документации.
Считать данные из csv-файла и превратить в DataFrame можно функцией read_csv.
Аргумент sep указывает разделитесь столбцов. Существует ещё масса способов сформировать DataFrame из различных источников, но наиболее часто используют CSV, Excel и SQL. Например, с помощью функции read_sql, pandas может выполнить SQL запрос и на основе ответа от базы данных сформировать необходимый DataFrame. За более подробной информацией стоит обратиться к официальной документации.
Группировка и агрегирование в pandas
Необходимо подсчитать, сколько женщин и мужчин выжило, а сколько нет. В этом нам поможет метод .groupby.
А теперь проанализируем в разрезе класса кабины:
Сводные таблицы в pandas
В качестве индекса теперь у нас будет пол человека, колонками станут значения из PClass, функцией агрегирования будет count (подсчёт количества записей) по колонке Name.
Анализ временных рядов
В pandas очень удобно анализировать временные ряды. В качестве показательного примера я буду использовать цену на акции корпорации Apple за 5 лет по дням. Файл с данными можно скачать тут.
Здесь мы формируем DataFrame с DatetimeIndex по колонке Date и сортируем новый индекс в правильном порядке для работы с выборками. Если колонка имеет формат даты и времени отличный от ISO8601, то для правильного перевода строки в нужный тип, можно использовать метод pandas.to_datetime.
Давайте теперь узнаем среднюю цену акции (mean) на закрытии (Close):
А если взять промежуток с февраля 2012 по февраль 2015 и посчитать среднее:
А что если нам нужно узнать среднюю цену закрытия по неделям?!
Resampling мощный инструмент при работе с временными рядами (time series), помогающий переформировать выборку так, как удобно вам. Метод resample первым аргументом принимает строку rule. Все доступные значения можно найти в документации.
Визуализация данных в pandas
Для визуального анализа данных, pandas использует библиотеку matplotlib. Продемонстрирую простейший способ визуализации в pandas на примере с акциями Apple.
Берём цену закрытия в промежутке между 2012 и 2017.
И видим вот такую картину:
По оси X, если не задано явно, всегда будет индекс. По оси Y в нашем случае цена закрытия. Если внимательно посмотреть, то в 2014 году цена на акцию резко упала, это событие было связано с тем, что Apple проводила сплит 7 к 1. Так мало кода и уже более-менее наглядный анализ 😉
Эта заметка демонстрирует лишь малую часть возможностей pandas. Со своей стороны я постараюсь по мере своих сил обновлять и дополнять её.
Полезные ссылки
💌 Присоединяйтесь к рассылке
Понравился контент? Пожалуйста, подпишись на рассылку.
Изучаем pandas. Урок 2. Структуры данных Series и DataFrame
Во втором уроке мы познакомимся со структурами данных pandas – это Series и DataFrame. Основное внимание будет уделено вопросам создания и получения доступа к элементам данных структур, а также общим понятиям, которые позволят более интуитивно работать с ними в будущем.
Введение
Структура данных Series
Пора переходить к практике!
Импортируем нужные нам библиотеки.
Создать структуру Series можно на базе различных типов данных:
Конструктор класса Series выглядит следующим образом:
data – массив, словарь или скалярное значение, на базе которого будет построен Series;
copy – создает копию массива данных, если параметр равен True в ином случае ничего не делает.
В большинстве случаев, при создании Series, используют только первые два параметра. Рассмотрим различные варианты как это можно сделать.
Создание Series из списка Python
Самый простой способ создать Series – это передать в качестве единственного параметра в конструктор класса список Python.
Обратите внимание на левый столбец, в нем содержатся метки, которые мы передали в качестве index параметра при создании структуры. Правый столбец – это по-прежнему элементы нашей структуры.
Создание Series из ndarray массива из numpy
Создадим простой массив из пяти чисел, аналогичный списку из предыдущего раздела. Библиотеки pandas и numpy должны быть предварительно импортированы.
Теперь создадим Series с буквенными метками.
Создание Series из словаря (dict)
Еще один способ создать структуру Series – это использовать словарь для одновременного задания меток и значений.
Создание Series с использованием константы
Рассмотрим еще один способ создания структуры. На этот раз значения в ячейках структуры будут одинаковыми.
В созданной структуре Series имеется три элемента с одинаковым содержанием.
Работа с элементами Series
Можно использовать метку, тогда работа с Series будет похожа на работу со словарем (dict) в Python.
Доступно получение slice’ов.
В поле для индекса можно поместить условное выражение.
Со структурами Series можно работать как с векторами: складывать, умножать вектор на число и т.п.
Структура данных DataFrame
Если Series представляет собой одномерную структуру, которую для себя можно представить как таблицу с одной строкой, то DataFrame – это уже двумерная структура – полноценная таблица с множеством строк и столбцов.
Конструктор класса DataFrame выглядит так:
index – список меток для записей (имена строк таблицы);
columns – список меток для полей (имена столбцов таблицы);
copy – создает копию массива данных, если параметр равен True в ином случае ничего не делает.
Структуру DataFrame можно создать на базе:
Создание DataFrame из словаря
В данном случае будет использоваться одномерный словарь, элементами которого будут списки, структуры Series и т.д.
Создание DataFrame из списка словарей
Создание DataFrame из двумерного массива
Работа с элементами DataFrame
Основные подходы представлены в таблице ниже.
Операция | Синтаксис | Возвращаемый результат |
Выбор столбца | df[col] | Series |
Выбор строки по метке | df.loc[label] | Series |
Выбор строки по индексу | df.iloc[loc] | Series |
Слайс по строкам | df[0:4] | DataFrame |
Выбор строк, отвечающих условию | df[bool_vec] | DataFrame |
Теперь посмотрим, как использовать данные операций на практике.
Операция: выбор столбца.
Операция: выбор строки по метке.
Операция: выбор строки по индексу.
Операция: slice по строкам.
Операция: выбор строк, отвечающих условию.
P.S.
Изучаем pandas. Урок 2. Структуры данных Series и DataFrame : 6 комментариев
Опечатка: случае[т]
В большинстве случает, при создании Series
P.S. Спасибо за статью!
> Конструктор класса Series выглядит следующим образом:
> … fastpath=False
Про этот параметр ничего не сказали.
И слово “slice”, которое вы как только не склоняете здесь и далее в книге, переводится как “срез”. Это вполне себе русское и подходящее по смыслу слово.
Как мне кажется, ‘slice’ стало уже сленговым словом, и его вполне можно употреблять. Но слово ‘срез’ звучит тоже не плохо))) В данном случае выбор был сделан в пользу первого.