Как поменять местами столбцы в pandas

от admin

Как изменить порядок столбцов DataFrame

Мы расскажем, как изменить порядок следования колонок DataFrame , с помощью различных методов, таких как назначение названий колонок в нужном нам порядке, с помощью insert и reindex .

Список колонок в новом желаемом порядке в Pandas

Самый простой способ — переназначить DataFrame со списком столбцов , или просто назначить имена столбцов в том порядке, в котором мы их хотим:

Изменение порядка столбцов в DataFrame Pandas

Вы можете изменить порядок столбцов, вызвав DataFrame.reindex() в исходном DataFrame с измененным списком столбцов в качестве аргумента.

Функция reindex() возвращает новый DataFrame с заданным порядком столбцов.

В следующей программе мы возьмем DataFrame со столбцами a, b, c и изменим порядок столбцов на a, c, b.

Метод 2: использование индексации

Индексирование DataFrame может использоваться для изменения порядка столбцов в данном DataFrame.

Ниже приведен синтаксис для использования индексации DataFrame.

В следующей программе мы возьмем DataFrame со столбцами a, b, c и изменим порядок столбцов на a, c, b.

Метод 3: использование конструктора

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

Ниже приведен синтаксис для создания DataFrame с обновленным порядком столбцов.

В следующей программе мы возьмем DataFrame со столбцами a, b, c и изменим порядок столбцов на a, c, b.

В этом руководстве по Python мы узнали, как изменить порядок столбцов в DataFrame.

Как изменить порядок столбцов в PandaS DataFrame?

Вы можете изменить порядок столбцов, вызывая dataframe.reindex () в исходном файле dataframe с переставленным списком столбца в качестве аргумента.

Функция Reindex () возвращает новый DataFrame с заданным порядком столбцов.

В следующей программе мы возьмем dataframe с столбцами A, B, C и изменить порядок столбцов в A, C, B Отказ

Метод 2 – Использование индексации DataFrame

Индексирование DataFrame можно использовать изменить порядок столбцов в данном dataframe.

Ниже приведен синтаксис для использования индексации DataFrame.

В следующей программе мы возьмем dataframe с столбцами A, B, C и изменить порядок столбцов в A, C, B Отказ

Способ 3 – Использование конструктора DataFrame

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

Ниже приведен синтаксис для создания DataFrame с обновленным порядком столбца.

В следующей программе мы возьмем dataframe с столбцами A, B, C и изменить порядок столбцов в A, C, B Отказ

Резюме

В этом учебном пособии Python мы узнали, как изменить порядок столбцов в DataFrame.

How To Change The Order of Columns In a Pandas DataFrame

Changing the column order and moving columns to the front in pandas DataFrames

Introduction

Reordering columns in pandas DataFrames is one of the most common operations we want to perform. This is usually useful when it comes down to presenting results to other people as we need to order (at least a few) columns in some logical order.

Читать:
Как увеличить textbox c

In today’s article we are going to discuss how to change the order of columns in pandas DataFrames using

  • slicing of the original frame — mostly relevant when you need to re-order most of the columns
  • insert() method — if you want to insert a single column into a specified index
  • set_index() — if you need to move a column to the front of the DataFrame
  • and, reindex() method — mostly relevant to cases where you can specify column indices in the order you wish them to appear (e.g. in alphabetical order)

First, let’s create an example DataFrame that we’ll reference throughout this guide.

Using slicing

The easiest way is to slice the original DataFrame using a list containing the column names in the new order you wish them to follow:

This method is probably good enough if you want to re-order most of the columns’ names (and probably your DataFrame does have too many columns).

Using insert() method

If you need to insert column into DataFrame at specified location then pandas.DataFrame.insert() should do the trick. However, you should make sure that the column is first taken out of the original DataFrame otherwise a ValueError will be raised with the following message:

Therefore, before calling insert() we first need to do a pop() over the DataFrame in order to drop the column from the original DataFrame and retain its information. For instance, if we want to place colD as the first column of the frame we first need to pop() the column and then insert it back, this time to the desired index.

Using set_index() method

If you want to move a column to the front of a pandas DataFrame, then set_index() is your friend.

First, you specify the column we wish to move to the front, as the index of the DataFrame and then reset the index so that the old index is added as a column, and a new sequential index is used. Again, notice how we pop() the column so that it gets dropped before is being added as an index. This is required otherwise a name collision will occur when attempting to make the old index the first column of the DataFrame.

Using reindex() method

Finally, if you want to specify column indices in the order you wish them to appear (e.g. in alphabetical order) you can use reindex() method to conform the DataFrame to new index.

For example, let’s suppose we need to order the column names alphabetically in descending order

Note that the above is equivalent to

Final Thoughts

In today’s short guide we discussed how to change the order of columns in pandas DataFrames in many different ways. Make sure you pick the right method based on your specific requirements.

Похожие статьи