Что делает конструктор pd dataframe

Обновлено: 29.04.2024

Python Pandas DataFrame — это широко используемая структура данных, которая работает с двумерным массивом с маркированными осями (строками и столбцами). DataFrame определяется как стандартный способ хранения данных с двумя разными индексами, т. е. индексом строки и индексом столбца. Он состоит из следующих свойств:

  • Столбцы могут быть разнородными типами, такими как int, bool и т. д.
  • Его можно рассматривать как словарь структуры Series, в котором индексируются как строки, так и столбцы. Он обозначается как «столбцы» в случае столбцов и «индекс» в случае строк.

Параметры и описание

data: состоит из различных форм, таких как ndarray, ряд, карта, константы, списки, массив.

index: индекс np.arrange(n) по умолчанию используется для меток строк, если индекс не передается.

columns: синтаксис по умолчанию — np.arrange(n) для меток столбцов. Он показывает только true, если индекс не передан.

dtype: относится к типу данных каждого столбца.

copy(): используется для копирования данных.

Python Pandas DataFrame

Создание фрейма данных

Мы можем создать DataFrame следующими способами:

  • dict
  • Lists
  • Numpy ndarrrays
  • Series
  • Создание пустого DataFrame.

В приведенном ниже коде показано, как создать пустой DataFrame в Pandas:

Объяснение: В приведенном выше коде мы импортировали библиотеку pandas с псевдонимом pd, а затем определили переменную с именем df, которая состоит из пустого фрейма данных. Наконец, мы напечатали его, передав df в print.

Мы можем легко создать DataFrame в Pandas, используя list.

Объяснение: В приведенном выше коде мы определили переменную с именем “x”, состоящую из строковых значений. Конструктор DataFrame вызывается для списка для печати значений.

Объяснение: В приведенном выше коде мы определили словарь с именем «info», который состоит из списка ID и отдела. Для печати значений мы должны вызвать информационный словарь через переменную с именем df и передать ее в качестве аргумента в print().

Объяснение: В приведенном выше коде словарь с именем «info» состоит из двух серий с соответствующим индексом. Для печати значений мы должны вызвать информационный словарь через переменную с именем d1 и передать ее в качестве аргумента в print().

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

Мы можем выбрать любой столбец из DataFrame. Вот код, который демонстрирует, как выбрать столбец из DataFrame.

Объяснение: В приведенном выше коде словарь с именем «info» состоит из двух серий с соответствующим индексом. Позже мы вызвали информационный словарь через переменную d1 и выбрали «один» ряд из DataFrame, передав его в функцию print().

Добавление столбца

Мы также можем добавить любой новый столбец в существующий DataFrame. В приведенном ниже коде показано, как добавить любой новый столбец в существующий DataFrame:

Объяснение: В приведенном выше коде словарь с именем f состоит из двух серий с соответствующим индексом. Позже мы вызвали информационный словарь через переменную df.

Чтобы добавить новый столбец в существующий объект DataFrame, мы передали новую серию, содержащую некоторые значения, относящиеся к его индексу, и распечатали результат с помощью функции print().

Мы можем добавить новые столбцы, используя существующий DataFrame. Добавлен столбец «четыре», в котором хранится результат сложения двух столбцов, т. е. первого и третьего.

Удаление столбца

Мы также можем удалить любой столбец из существующего DataFrame. Этот код помогает продемонстрировать, как можно удалить столбец из существующего фрейма данных:

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

В первом случае мы использовали функцию удаления для удаления столбца «один» из фрейма данных, тогда как во втором случае мы использовали функцию всплывающего окна для удаления столбца «два» из фрейма данных.

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

Мы можем легко выбрать, добавить или удалить любую строку в любое время. Прежде всего, мы разберемся с выбором строки.

Выбор строки

Давайте посмотрим, как мы можем выбрать строку, используя следующие способы.

Мы можем выбрать любую строку, передав метку строки функции loc.

Объяснение: В приведенном выше коде словарь с именем info состоит из двух серий с соответствующим индексом.

Для выбора строки мы передали метку строки функции loc.

Строки также можно выбрать, передав целочисленное местоположение функции iloc.

Объяснение: В приведенном выше коде мы определили словарь с именем info, который состоит из двух серий с соответствующим индексом.

Для выбора строки мы передали целочисленное местоположение функции iloc.

Это еще один способ выбрать несколько строк с помощью оператора ‘:’.

Объяснение: В приведенном выше коде мы определили диапазон от 2:5 для выбора строки, а затем вывели его значения на консоль.

Добавление строк

Мы можем легко добавлять новые строки в DataFrame, используя функцию добавления. Он добавляет новые строки в конце.

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

Удаление строк

Мы можем удалить любые строки из DataFrame, используя метку индекса. Если в этом случае метка дублируется, несколько строк будут удалены.

Объяснение: В приведенном выше коде мы определили два отдельных списка, содержащих несколько строк и столбцов.

Здесь мы определили метку индекса строки, которую необходимо удалить из списка.

Two-dimensional, size-mutable, potentially heterogeneous tabular data.

Attributes and underlying data¶

Axes

The index (row labels) of the DataFrame.

The column labels of the DataFrame.

Return the dtypes in the DataFrame.

Print a concise summary of a DataFrame.

Return a subset of the DataFrame's columns based on the column dtypes.

Return a Numpy representation of the DataFrame.

Return a list representing the axes of the DataFrame.

Return an int representing the number of axes / array dimensions.

Return an int representing the number of elements in this object.

Return a tuple representing the dimensionality of the DataFrame.

Return the memory usage of each column in bytes.

Indicator whether Series/DataFrame is empty.

Return a new object with updated flags.

Conversion¶

Cast a pandas object to a specified dtype dtype .

Convert columns to best possible dtypes using dtypes supporting pd.NA .

Attempt to infer better dtypes for object columns.

Make a copy of this object's indices and data.

Return the bool of a single element Series or DataFrame.

Indexing, iteration¶

Return the first n rows.

Access a single value for a row/column label pair.

Access a single value for a row/column pair by integer position.

Access a group of rows and columns by label(s) or a boolean array.

Purely integer-location based indexing for selection by position.

Insert column into DataFrame at specified location.

Iterate over info axis.

Iterate over (column name, Series) pairs.

Iterate over (column name, Series) pairs.

Get the 'info axis' (see Indexing for more).

Iterate over DataFrame rows as (index, Series) pairs.

Iterate over DataFrame rows as namedtuples.

(DEPRECATED) Label-based "fancy indexing" function for DataFrame.

Return item and drop from frame.

Return the last n rows.

DataFrame.xs (key[, axis, level, drop_level])

Return cross-section from the Series/DataFrame.

Get item from object for given key (ex: DataFrame column).

Whether each element in the DataFrame is contained in values.

Replace values where the condition is False.

Replace values where the condition is True.

Query the columns of a DataFrame with a boolean expression.

For more information on .at , .iat , .loc , and .iloc , see the indexing documentation .

Binary operator functions¶

DataFrame.add (other[, axis, level, fill_value])

Get Addition of dataframe and other, element-wise (binary operator add ).

DataFrame.sub (other[, axis, level, fill_value])

Get Subtraction of dataframe and other, element-wise (binary operator sub ).

DataFrame.mul (other[, axis, level, fill_value])

Get Multiplication of dataframe and other, element-wise (binary operator mul ).

DataFrame.div (other[, axis, level, fill_value])

Get Floating division of dataframe and other, element-wise (binary operator truediv ).

Get Floating division of dataframe and other, element-wise (binary operator truediv ).

Get Integer division of dataframe and other, element-wise (binary operator floordiv ).

DataFrame.mod (other[, axis, level, fill_value])

Get Modulo of dataframe and other, element-wise (binary operator mod ).

DataFrame.pow (other[, axis, level, fill_value])

Get Exponential power of dataframe and other, element-wise (binary operator pow ).

Compute the matrix multiplication between the DataFrame and other.

DataFrame.radd (other[, axis, level, fill_value])

Get Addition of dataframe and other, element-wise (binary operator radd ).

DataFrame.rsub (other[, axis, level, fill_value])

Get Subtraction of dataframe and other, element-wise (binary operator rsub ).

DataFrame.rmul (other[, axis, level, fill_value])

Get Multiplication of dataframe and other, element-wise (binary operator rmul ).

DataFrame.rdiv (other[, axis, level, fill_value])

Get Floating division of dataframe and other, element-wise (binary operator rtruediv ).

Get Floating division of dataframe and other, element-wise (binary operator rtruediv ).

Get Integer division of dataframe and other, element-wise (binary operator rfloordiv ).

DataFrame.rmod (other[, axis, level, fill_value])

Get Modulo of dataframe and other, element-wise (binary operator rmod ).

DataFrame.rpow (other[, axis, level, fill_value])

Get Exponential power of dataframe and other, element-wise (binary operator rpow ).

Get Less than of dataframe and other, element-wise (binary operator lt ).

Get Greater than of dataframe and other, element-wise (binary operator gt ).

Get Less than or equal to of dataframe and other, element-wise (binary operator le ).

Get Greater than or equal to of dataframe and other, element-wise (binary operator ge ).

Get Not equal to of dataframe and other, element-wise (binary operator ne ).

Get Equal to of dataframe and other, element-wise (binary operator eq ).

Perform column-wise combine with another DataFrame.

Update null elements with value in the same location in other .

Function application, GroupBy & window¶

Apply a function along an axis of the DataFrame.

Apply a function to a Dataframe elementwise.

Apply chainable functions that expect Series or DataFrames.

Aggregate using one or more operations over the specified axis.

Aggregate using one or more operations over the specified axis.

Call func on self producing a DataFrame with the same axis shape as self.

Group DataFrame using a mapper or by a Series of columns.

Provide rolling window calculations.

Provide expanding window calculations.

Provide exponentially weighted (EW) calculations.

Computations / descriptive stats¶

Return a Series/DataFrame with absolute numeric value of each element.

DataFrame.all ([axis, bool_only, skipna, level])

Return whether all elements are True, potentially over an axis.

DataFrame.any ([axis, bool_only, skipna, level])

Return whether any element is True, potentially over an axis.

Trim values at input threshold(s).

Compute pairwise correlation of columns, excluding NA/null values.

Compute pairwise correlation.

Count non-NA cells for each column or row.

Compute pairwise covariance of columns, excluding NA/null 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.

Evaluate a string describing operations on DataFrame columns.

Return unbiased kurtosis over requested axis.

Return unbiased kurtosis over requested axis.

Return the mean absolute deviation of the values over the requested axis.

Return the maximum of the values over the requested axis.

Return the mean of the values over the requested axis.

Return the median of the values over the requested axis.

Return the minimum of the values over the requested axis.

Get the mode(s) of each element along the selected axis.

Percentage change between the current and a prior element.

Return the product of the values over the requested axis.

Return the product of the values over the requested axis.

Return values at the given quantile over requested axis.

Compute numerical data ranks (1 through n) along axis.

Round a DataFrame to a variable number of decimal places.

Return unbiased standard error of the mean over requested axis.

Return unbiased skew over requested axis.

Return the sum of the values over the requested axis.

Return sample standard deviation over requested axis.

Return unbiased variance over requested axis.

Count number of distinct elements in specified axis.

Return a Series containing counts of unique rows in the DataFrame.

Reindexing / selection / label manipulation¶

Prefix labels with string prefix .

Suffix labels with string suffix .

Align two objects on their axes with the specified join method.

Select values at particular time of day (e.g., 9:30AM).

Select values between particular times of the day (e.g., 9:00-9:30 AM).

Drop specified labels from rows or columns.

Return DataFrame with duplicate rows removed.

Return boolean Series denoting duplicate rows.

Test whether two objects contain the same elements.

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 the first n rows.

Return index of first occurrence of maximum over requested axis.

Return index of first occurrence of minimum over requested axis.

Select final periods of time series data based on a date offset.

Conform Series/DataFrame to new index with optional filling logic.

Return an object with matching indices as other object.

Alter axes labels.

Set the name of the axis for the index or columns.

Reset the index, or a level of it.

Return a random sample of items from an axis of object.

Assign desired index to given axis.

Set the DataFrame index using existing columns.

Return the last n rows.

Return the elements in the given positional indices along an axis.

Truncate a Series or DataFrame before and after some index value.

Missing data handling¶

Synonym for DataFrame.fillna() with method='bfill' .

DataFrame.bfill ([axis, inplace, limit, downcast])

Synonym for DataFrame.fillna() with method='bfill' .

Remove missing values.

DataFrame.ffill ([axis, inplace, limit, downcast])

Synonym for DataFrame.fillna() with method='ffill' .

Fill NA/NaN values using the specified method.

Fill NaN values using an interpolation method.

Detect missing values.

DataFrame.isnull is an alias for DataFrame.isna.

Detect existing (non-missing) values.

DataFrame.notnull is an alias for DataFrame.notna.

DataFrame.pad ([axis, inplace, limit, downcast])

Synonym for DataFrame.fillna() with method='ffill' .

Replace values given in to_replace with value .

Reshaping, sorting, transposing¶

Return Series/DataFrame with requested index / column level(s) removed.

Return reshaped DataFrame organized by given index / column values.

Create a spreadsheet-style pivot table as a DataFrame.

Rearrange index levels using input order.

Sort by the values along either axis.

Sort object by labels (along an axis).

Return the first n rows ordered by columns in descending order.

Return the first n rows ordered by columns in ascending order.

Swap levels i and j in a MultiIndex .

Stack the prescribed level(s) from columns to index.

Pivot a level of the (necessarily hierarchical) index labels.

Interchange axes and swap values axes appropriately.

Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.

Transform each element of a list-like to a row, replicating index values.

Squeeze 1 dimensional axis objects into scalars.

Return an xarray object from the pandas object.

Transpose index and columns.

Combining / comparing / joining / merging¶

(DEPRECATED) Append rows of other to the end of caller, returning a new object.

Assign new columns to a DataFrame.

Compare to another DataFrame and show the differences.

Join columns of another DataFrame.

Merge DataFrame or named Series objects with a database-style join.

Modify in place using non-NA values from another DataFrame.

Time Series-related¶

Convert time series to specified frequency.

Return the last row(s) without any NaNs before where .

Shift index by desired number of periods with an optional time freq .

(DEPRECATED) Equivalent to shift without copying data.

(DEPRECATED) Shift the time index, using the index's frequency if available.

Return index for first non-NA value or None, if no non-NA value is found.

Return index for last non-NA value or None, if no non-NA value is found.

Resample time-series data.

Convert DataFrame from DatetimeIndex to PeriodIndex.

Cast to DatetimeIndex of timestamps, at beginning of period.

Convert tz-aware axis to target time zone.

Localize tz-naive index of a Series or DataFrame to target time zone.

Flags¶

Flags refer to attributes of the pandas object. Properties of the dataset (like the date is was recorded, the URL it was accessed from, etc.) should be stored in DataFrame.attrs .

Flags that apply to pandas objects.

Metadata¶

DataFrame.attrs is a dictionary for storing global metadata for this DataFrame.

DataFrame.attrs is considered experimental and may change without warning.

Dictionary of global attributes of this dataset.

Plotting¶

DataFrame.plot is both a callable method and a namespace attribute for specific plotting methods of the form DataFrame.plot. .

DataFrame plotting accessor and method

Draw a stacked area plot.

Vertical bar plot.

Make a horizontal bar plot.

Make a box plot of the DataFrame columns.

Generate Kernel Density Estimate plot using Gaussian kernels.

Generate a hexagonal binning plot.

Draw one histogram of the DataFrame's columns.

Generate Kernel Density Estimate plot using Gaussian kernels.

Plot Series or DataFrame as lines.

Generate a pie plot.

Create a scatter plot with varying marker point size and color.

Make a box plot from DataFrame columns.

Make a histogram of the DataFrame's columns.

Sparse accessor¶

Sparse-dtype specific methods and attributes are provided under the DataFrame.sparse accessor.

We’ll start with a quick, non-comprehensive overview of the fundamental data structures in pandas to get you started. The fundamental behavior about data types, indexing, axis labeling, and alignment apply across all of the objects. To get started, import NumPy and load pandas into your namespace:

Fundamentally, data alignment is intrinsic. The link between labels and data will not be broken unless done so explicitly by you.

We’ll give a brief intro to the data structures, then consider all of the broad categories of functionality and methods in separate sections.

Series¶

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. The basic method to create a Series is to call:

Here, data can be many different things:

a scalar value (like 5)

The passed index is a list of axis labels. Thus, this separates into a few cases depending on what data is:

From ndarray

If data is an ndarray, index must be the same length as data. If no index is passed, one will be created having values [0, . len(data) - 1] .

pandas supports non-unique index values. If an operation that does not support duplicate index values is attempted, an exception will be raised at that time.

From dict

Series can be instantiated from dicts:

If an index is passed, the values in data corresponding to the labels in the index will be pulled out.

NaN (not a number) is the standard missing data marker used in pandas.

From scalar value

If data is a scalar value, an index must be provided. The value will be repeated to match the length of index.

Series is ndarray-like¶

Series acts very similarly to a ndarray and is a valid argument to most NumPy functions. However, operations such as slicing will also slice the index.

We will address array-based indexing like s[[4, 3, 1]] in section on indexing .

Like a NumPy array, a pandas Series has a single dtype .

This is often a NumPy dtype. However, pandas and 3rd-party libraries extend NumPy’s type system in a few places, in which case the dtype would be an ExtensionDtype . Some examples within pandas are Categorical data and Nullable integer data type . See dtypes for more.

If you need the actual array backing a Series , use Series.array .

Accessing the array can be useful when you need to do some operation without the index (to disable automatic alignment , for example).

Series.array will always be an ExtensionArray . Briefly, an ExtensionArray is a thin wrapper around one or more concrete arrays like a numpy.ndarray . pandas knows how to take an ExtensionArray and store it in a Series or a column of a DataFrame . See dtypes for more.

While Series is ndarray-like, if you need an actual ndarray, then use Series.to_numpy() .

Even if the Series is backed by a ExtensionArray , Series.to_numpy() will return a NumPy ndarray.

Series is dict-like¶

A Series is also like a fixed-size dict in that you can get and set values by index label:

If a label is not contained in the index, an exception is raised:

Using the Series.get() method, a missing label will return None or specified default:

These labels can also be accessed by attribute .

Vectorized operations and label alignment with Series¶

When working with raw NumPy arrays, looping through value-by-value is usually not necessary. The same is true when working with Series in pandas. Series can also be passed into most NumPy methods expecting an ndarray.

A key difference between Series and ndarray is that operations between Series automatically align the data based on label. Thus, you can write computations without giving consideration to whether the Series involved have the same labels.

The result of an operation between unaligned Series will have the union of the indexes involved. If a label is not found in one Series or the other, the result will be marked as missing NaN . Being able to write code without doing any explicit data alignment grants immense freedom and flexibility in interactive data analysis and research. The integrated data alignment features of the pandas data structures set pandas apart from the majority of related tools for working with labeled data.

In general, we chose to make the default result of operations between differently indexed objects yield the union of the indexes in order to avoid loss of information. Having an index label, though the data is missing, is typically important information as part of a computation. You of course have the option of dropping labels with missing data via the dropna function.

Name attribute¶

Series also has a name attribute:

The Series name can be assigned automatically in many cases, in particular, when selecting a single column from a DataFrame , the name will be assigned the column label.

You can rename a Series with the pandas.Series.rename() method.

Note that s and s2 refer to different objects.

DataFrame¶

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object. Like Series, DataFrame accepts many different kinds of input:

Dict of 1D ndarrays, lists, dicts, or Series

Along with the data, you can optionally pass index (row labels) and columns (column labels) arguments. If you pass an index and / or columns, you are guaranteeing the index and / or columns of the resulting DataFrame. Thus, a dict of Series plus a specific index will discard all data not matching up to the passed index.

If axis labels are not passed, they will be constructed from the input data based on common sense rules.

From dict of Series or dicts¶

The resulting index will be the union of the indexes of the various Series. If there are any nested dicts, these will first be converted to Series. If no columns are passed, the columns will be the ordered list of dict keys.

The row and column labels can be accessed respectively by accessing the index and columns attributes:

When a particular set of columns is passed along with a dict of data, the passed columns override the keys in the dict.

From dict of ndarrays / lists¶

The ndarrays must all be the same length. If an index is passed, it must also be the same length as the arrays. If no index is passed, the result will be range(n) , where n is the array length.

From structured or record array¶

This case is handled identically to a dict of arrays.

DataFrame is not intended to work exactly like a 2-dimensional NumPy ndarray.

From a list of dicts¶

From a dict of tuples¶

You can automatically create a MultiIndexed frame by passing a tuples dictionary.

From a Series¶

The result will be a DataFrame with the same index as the input Series, and with one column whose name is the original name of the Series (only if no other column name provided).

From a list of namedtuples¶

The field names of the first namedtuple in the list determine the columns of the DataFrame . The remaining namedtuples (or tuples) are simply unpacked and their values are fed into the rows of the DataFrame . If any of those tuples is shorter than the first namedtuple then the later columns in the corresponding row are marked as missing values. If any are longer than the first namedtuple , a ValueError is raised.

From a list of dataclasses¶

New in version 1.1.0.

Data Classes as introduced in PEP557, can be passed into the DataFrame constructor. Passing a list of dataclasses is equivalent to passing a list of dictionaries.

Please be aware, that all values in the list should be dataclasses, mixing types in the list would result in a TypeError .

Missing data

To construct a DataFrame with missing data, we use np.nan to represent missing values. Alternatively, you may pass a numpy.MaskedArray as the data argument to the DataFrame constructor, and its masked entries will be considered missing. See Missing data for more.

Alternate constructors¶

DataFrame.from_dict

DataFrame.from_dict() takes a dict of dicts or a dict of array-like sequences and returns a DataFrame. It operates like the DataFrame constructor except for the orient parameter which is 'columns' by default, but which can be set to 'index' in order to use the dict keys as row labels.

If you pass orient='index' , the keys will be the row labels. In this case, you can also pass the desired column names:

DataFrame.from_records

DataFrame.from_records() takes a list of tuples or an ndarray with structured dtype. It works analogously to the normal DataFrame constructor, except that the resulting DataFrame index may be a specific field of the structured dtype.

Column selection, addition, deletion¶

You can treat a DataFrame semantically like a dict of like-indexed Series objects. Getting, setting, and deleting columns works with the same syntax as the analogous dict operations:

Columns can be deleted or popped like with a dict:

When inserting a scalar value, it will naturally be propagated to fill the column:

When inserting a Series that does not have the same index as the DataFrame , it will be conformed to the DataFrame’s index:

You can insert raw ndarrays but their length must match the length of the DataFrame’s index.

By default, columns get inserted at the end. DataFrame.insert() inserts at a particular location in the columns:

Assigning new columns in method chains¶

Inspired by dplyr’s mutate verb, DataFrame has an assign() method that allows you to easily create new columns that are potentially derived from existing columns.

In the example above, we inserted a precomputed value. We can also pass in a function of one argument to be evaluated on the DataFrame being assigned to.

assign() always returns a copy of the data, leaving the original DataFrame untouched.

Passing a callable, as opposed to an actual value to be inserted, is useful when you don’t have a reference to the DataFrame at hand. This is common when using assign() in a chain of operations. For example, we can limit the DataFrame to just those observations with a Sepal Length greater than 5, calculate the ratio, and plot:

../_images/basics_assign.jpg

Since a function is passed in, the function is computed on the DataFrame being assigned to. Importantly, this is the DataFrame that’s been filtered to those rows with sepal length greater than 5. The filtering happens first, and then the ratio calculations. This is an example where we didn’t have a reference to the filtered DataFrame available.

The function signature for assign() is simply **kwargs . The keys are the column names for the new fields, and the values are either a value to be inserted (for example, a Series or NumPy array), or a function of one argument to be called on the DataFrame . A copy of the original DataFrame is returned, with the new values inserted.

The order of **kwargs is preserved. This allows for dependent assignment, where an expression later in **kwargs can refer to a column created earlier in the same assign() .

In the second expression, x['C'] will refer to the newly created column, that’s equal to dfa['A'] + dfa['B'] .

Фрейм данных – это двухмерный набор данных, структура, в которой данные хранятся в табличной форме. Наборы данных упорядочены по строкам и столбцам; мы можем хранить несколько наборов данных во фрейме данных. Мы можем выполнять различные арифметические операции, такие как добавление выбора столбца или строки и столбцов или строк во фрейме данных.

Мы можем импортировать DataFrames из внешнего хранилища; эти хранилища могут быть базой данных SQL, файлом CSV или файлом Excel. Мы также можем использовать списки, словарь, список словаря и т. д.

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

Пустой фрейм данных

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

Метод – 2: создать фрейм данных с помощью списка

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

Метод – 3: Dataframe из dict ndarray / lists

Dict ndarray / lists можно использовать для создания фрейма данных, все ndarray должны иметь одинаковую длину. По умолчанию индекс будет диапазоном(n); где n обозначает длину массива.

Метод – 4: Создание фрейма данных индексов с использованием массивов

Давайте разберемся в примере создания фрейм данных индексов с использованием массивов.

В приведенном выше коде мы определили имя столбца с различными названиями автомобилей и их рейтингами. Мы использовали массив для создания индексов.

Метод – 5: Dataframe из списка dicts

Мы можем передать списки словарей в качестве входных данных для создания фрейма данных Pandas. Имена столбцов по умолчанию используются в качестве ключей.

Давайте разберемся в другом примере создания фрейма данных pandas из списка словарей с индексом строки и индексом столбца.

Рассмотрим пример создания фрейма данных путем передачи списков словарей и строк.

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

Метод – 6: с помощью функции zip()

Функция zip() используется для объединения двух списков. Давайте разберемся в следующем примере.

Метод – 7: из Dicts серии

Словарь можно передать для создания фрейма данных. Мы можем использовать Dicts of series, где последующий индекс представляет собой объединение всех серий переданного значения индекса. Давайте разберем на примере.

DataFrame — это специальная структура данных в очень популярной Python библиотеки pandas. Работа с библиотекой pandas часто заключается в том что нужно создать из данных DataFrame, а дальше что-то делать с этими данными, лежащими в DataFrame.

Есть несколько способов создать DataFrame.

Создать DataFrame из данных, записанных в коде программы

Самый простой способ создать DataFrame — это передать конструктору словарь. Ключи станут названиями колонок, а значения (в которых содержатся списки) станут данными в этих колонках.

Вот пример как это выглядит в Jupyter Notebook:


Но не всегда удобно задавать данные по столбцам. Можно создать DataFrame и из данных, которые разбиты по строкам. Для этого в конструктор нужно передать список в котором содержатся данные для строк. Вот пример создания DataFrame с данными как из прошлого примера, но по строкам, а не по столбцам:

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


Для того чтобы вместо чисел были осмысленные названия колонок нужно указать список названий в именованном аргументе columns:

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

Создать DataFrame из csv файла

Вот содержимое файла solar-system.csv:

Csv — это очень распространенный формат (расшифровывается как "comma separated values",— "значения разделенные запятыми"). В файле solar-system.csv в первой строчке находится заголовок с названиями столбцов, все остальные строки — это данные. Разделитель между элементами это символ запятая. Для того чтобы загрузить данные из этого файла в DataFrame нужно сказать:

Но иногда формат csv файла выглядит несколько иначе. Бывает что в качестве разделителя используется не запятая, а какой-то другой символ, например точка с запятой или символ табуляции (в это случае файл иногда бывает с расширением .tsv — "tab separated values"). read_csv можно указать какой разделитель использовать:

Бывает что в csv файле нет заголовка, в первой строке сразу идут данные. В таком случае нужно передать None в именованный параметр header:

Но в такой ситуации система не будет знать какие названия столбцов использовать и будут использованы цифры начиная с нуля. Для того чтобы установить имена колонок нужно передать параметр names:

Создать DataFrame из jsonl файла

Кроме csv еще есть достаточно популярный формат для хранения данных в текстовых файла — jsonl. JSON Lines. При использовании этого формата в каждой строчке файла содержится однострочный json. Это формат лучше чем csv, так как строго регламентирует что должно быть разделителем и как нужно экранировать.

Вот пример содержимого файла solar-system.jsonl:

Для того чтобы загрузить его в DataFrame нужно сказать:

Создать DataFrame из результата sql запроса

Вот пример кода, который загружает в DataFrame таблицу с результатом sql запроса из sqlite базы данных:

Создать DataFrame из файла в интернете

Иногда необходимо создать DataFrame с данными которые лежат где-то в интернете. Например, создать DataFrame из csv файла, который лежит на GitHub.

pandas.read_csv умеет рабоать не только с локальными файлами, но и с файлами, которые лежат в интернете. Вот как загрузить в DataFrame данные про страны из файла по ссылке:

Читайте также: