Rukovodstvo
статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.
Как переименовать столбец Pandas DataFrame в Python
Введение Pandas [https://pandas.pydata.org/] — это библиотека Python для анализа и обработки данных. Почти все операции в пандах вращаются вокруг DataFrames. Dataframe — это абстрактное представление двумерной таблицы, которая может содержать все виды данных. Они также позволяют нам давать имена всем столбцам, поэтому часто столбцы называются атрибутами или полями при использовании DataFrames. В этой статье мы увидим, как мы можем переименовать уже существующий столбец DataFrame.
Время чтения: 3 мин.
Вступление
Pandas — это библиотека Python для анализа и обработки данных. Почти все операции в pandas вращаются вокруг DataFrame s.
Dataframe — это абстрактное представление двумерной таблицы, которая может содержать все виды данных. Они также позволяют нам давать имена всем столбцам, поэтому часто столбцы называются атрибутами или полями при использовании DataFrames .
В этой статье мы увидим, как мы можем переименовать уже существующие DataFrame .
Есть два варианта управления именами столбцов DataFrame :
- Переименование столбцов существующего DataFrame
- Назначение имен пользовательских столбцов при создании нового DataFrame
Давайте посмотрим на оба метода.
Переименование столбцов существующего фрейма данных
У нас есть образец DataFrame ниже:
DataFrame df выглядит так:
Чтобы переименовать столбцы этого DataFrame , мы можем использовать метод rename() который принимает:
- Словарь в качестве columns содержащий сопоставление исходных имен столбцов с именами новых столбцов в виде пар ключ-значение
- boolean значение в качестве inplace , которое, если установлено в True , внесет изменения в исходный Dataframe
Давайте изменим имена столбцов в нашем DataFrame с Name, age на First Name, Age .
Теперь наш df содержит:
Назначьте имена столбцов при создании фрейма данных
Теперь мы обсудим, как назначать имена столбцам при создании DataFrame .
Это особенно полезно, когда вы создаете DataFrame из csv и хотите игнорировать имена столбцов заголовков и назначить свои собственные.
Передав список names , мы можем заменить уже существующий столбец заголовка нашим собственным. В списке должно быть имя для каждого столбца данных, в противном случае создается исключение.
Обратите внимание: если мы хотим переименовать только несколько столбцов, лучше использовать метод rename DataFrame после его создания.
Мы будем создавать DataFrame используя out.csv , который имеет следующее содержимое:
Обратите внимание, что первая строка в файле является строкой заголовка и содержит имена столбцов. Pandas по умолчанию назначает имена столбцов DataFrame из первой строки.
Следовательно, мы укажем игнорировать строку заголовка при создании нашего DataFrame и укажем имена столбцов в списке, который передается в аргумент names
Другой способ сделать это — указать имена столбцов в простом старом конструкторе DataFrame() .
Единственное отличие состоит в том, что теперь параметр, который принимает список имен column называется столбцом вместо names :
Это приводит к другому DataFrame :
Заключение
В этой статье мы быстро рассмотрели, как мы можем называть и переименовывать столбцы в DataFrame . Либо путем присвоения имен при DataFrame экземпляра DataFrame, либо путем переименования их после факта с помощью метода rename()
pandas.DataFrame.rename#
Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error.
See the user guide for more.
Parameters mapper dict-like or function
Dict-like or function transformations to apply to that axis’ values. Use either mapper and axis to specify the axis to target with mapper , or index and columns .
index dict-like or function
Alternative to specifying axis ( mapper, axis=0 is equivalent to index=mapper ).
columns dict-like or function
Alternative to specifying axis ( mapper, axis=1 is equivalent to columns=mapper ).
Axis to target with mapper . Can be either the axis name (‘index’, ‘columns’) or number (0, 1). The default is ‘index’.
copy bool, default True
Also copy underlying data.
inplace bool, default False
Whether to modify the DataFrame rather than creating a new one. If True then value of copy is ignored.
level int or level name, default None
In case of a MultiIndex, only rename labels in the specified level.
errors <‘ignore’, ‘raise’>, default ‘ignore’
If ‘raise’, raise a KeyError when a dict-like mapper , index , or columns contains labels that are not present in the Index being transformed. If ‘ignore’, existing keys will be renamed and extra keys will be ignored.
Returns DataFrame or None
DataFrame with the renamed axis labels or None if inplace=True .
If any of the labels is not found in the selected axis and “errors=’raise’”.
Set the name of the axis.
DataFrame.rename supports two calling conventions
We highly recommend using keyword arguments to clarify your intent.
How to Rename Pandas DataFrame Columns (with Examples)
Being able to rename columns in your Pandas DataFrame is an incredibly common task. In particular, being able to label your DataFrame columns in a meaningful way is useful to communicate your data better. Similarly, you have inherited a dataset from someone and the columns are mislabeled. In all of these cases, being able to rename your DataFrame’s columns is a useful skill.
In this tutorial, you’ll learn how to rename Pandas DataFrame columns. You’ll learn how to use the Pandas .rename() method as well as other useful techniques. For example, you’ll learn how to add a prefix to every column name.
By the end of this tutorial, you’ll have learned the following:
- How to rename a single column or all columns in a Pandas DataFrame using the .rename() method
- How to use the .columns attribute to rename columns in creative ways, such as by adding a prefix or suffix, or by lowercasing all columns
- How to replace or remove specific text or characters from all column names at once
- How to use mapper functions to rename Pandas DataFrame columns
Table of Contents
How to Rename Columns in a Pandas DataFrame
To rename columns in a Pandas DataFrame, you have two options: using the rename() method or the columns attribute. The .rename() method allows you to pass in existing labels and the ones you want to use. The .columns attribute allows you to specify a list of values to use as column labels.
Let’s look at the primary methods of renaming Pandas DataFrame columns in a bit more detail:
- The Pandas .rename() method allows you to rename DataFrame labels. In particular, you can pass in a mapping to rename column labels. This can either be a mapper function or a dictionary of column labels to use. This method is best when you want to relabel a single or a few columns.
- The Pandas .columns attribute allows you to pass in a list of values to use as the column names. This allows you to easily modify all column names by applying the same transformation to all column labels. This method is best when you want to rename all columns following the same type of transformation, such as lower-casing all column names or removing spaces.
Loading a Sample Pandas DataFrame
To follow along, let’s load a sample Pandas DataFrame. Feel free to copy and paste the code below into your favorite code editor. If you’re working with your own dataset – no problem! The results will, of course, vary.
We can see that we have a DataFrame with five different columns. Some of the columns are single words, while others are multiple words with spaces. Similarly, all of our column names are in title case, meaning that the first letter is capitalized.
Let’s dive into how to rename Pandas columns by first learning how to rename a single column.
How to Rename a Single Pandas DataFrame Column
To rename a single Pandas DataFrame column, we can use the Pandas .rename() method. The method, as the name implies, is used to rename labels in a DataFrame. Let’s take a quick look at how the method is written:
We can see that the function takes up to seven arguments. Some of these parameters are specific to renaming row (index) labels. Since we’re focusing on how to rename columns, let’s only focus on a subset of these.
In order to rename a single column in Pandas, we can use either the mapper= parameter or the columns= helper parameter. Because columns are along the first axis, if we want to use the mapper= parameter, we need to specify axis=1 . This, however, is a bit more complicated, in my opinion, than using the columns= convenience parameter.
Let’s take a look at how we can use the columns= parameter to rename a Pandas column by name:
We can see that by passing a dictionary of column mappings into the columns= parameter, we were able to rename a single Pandas column. This is the equivalent of having written df = df.rename(mapper=<'Birth City': 'City'>, axis=1) . However, not only is this clear, but it’s also faster to type!
Renaming a Single Pandas DataFrame Column by Position
Now, say you didn’t know what the first column was called, but you knew you wanted to change its name to something specific. The df.columns attribute returns a list of all of the column labels in a Pandas DataFrame. Because of this, we can pass in the mapping of the first column.
For example, if we wanted to change the first column to be named ‘id’ , we could write the following:
We can see that we were able to rename the first column of a DataFrame by using the .columns attribute. We’ll get back to using that attribute more in a minute. However, let’s now focus on how we can rename multiple columns at once.
How to Rename Multiple Pandas Columns with .rename()
Similar to renaming a single column in a DataFrame, we can use the .rename() method to rename multiple columns. In order to do this, we simply need to pass in a dictionary containing more key-value pairs.
Let’s see how we can rename multiple columns in a Pandas DataFrame with the .rename() method:
We can see that we were able to rename multiple columns in one go. At this point, I’ll note that if a column doesn’t exist, Pandas won’t (by default) throw an error – though you can change this, as you’ll learn later.
Let’s now take a look at a way to rename multiple columns using a list comprehension.
How to Use List Comprehensions to Rename Pandas DataFrame Columns
In this section, you’ll learn how to use list comprehensions to rename Pandas columns. This can be helpful when you want to rename columns in a similar style. This could include removing spaces or changing all cases to lowercase.
For example, if your column names have spaces, it can be impossible to use dot notation to select columns. Similarly, since selecting columns is case-sensitive, having different casing in your columns can make selecting them more difficult.
Let’s take a look at an example where we want to remove all spaces from our column headers:
Let’s break down what we’re doing in the code block above:
- We used a list comprehension to iterate over each column name in our DataFrame
- For each column label, we used the .replace() string method to replace all spaces with underscores
- We then also applied the .lower() method to change the string to its lowercase equivalent
It’s important to note here that we’re not reassigning this list to the DataFrame, but rather to the df.columns attribute. Since the attribute represents the column labels, we can assign a list of values directly to that attribute to overwrite column names.
Using a Mapper Function to Rename Pandas Columns
The Pandas .rename() method also allows you to pass in a mapper function directly into the mapper= parameter. Rather than needing to pass in a dictionary of label mappings, you can apply the same mapping transformation to each column label.
Say we simply wanted to lowercase all of our columns, we could do this using a mapper function directly passed into the .rename() method:
We use axis=’columns’ to specify that we want to apply this transformation to the columns. Similarly, you could write: axis=1 . We can see that this applied the transformation to all columns.
Keep in mind, because we’re using a string method, this will only work if your columns are all strings! If any of your columns are, say, just numbers, this method will raise a TypeError.
Using a Lambda Function to Rename Pandas Columns
You can also use custom lambda functions to pass in more complex transformations. This works in the same way as using a simple, built-in mapper function. However, it allows us to pass in custom transformations to our column names.
Let’s take a look at an example. If we wanted to use a lambda function to rename all of our columns by replacing spaces and lowercasing our characters, we could write:
We use axis=1 to specify that we want to apply this transformation to the columns. Similarly, you could write: axis=’columns’ .
Renaming Pandas DataFrame Columns In Place
You may have noticed that for all of our examples using the .rename() method, we have reassigned the DataFrame to itself. We can avoid having to do this by using the boolean inplace= parameter in our method call. Let’s use our previous example to illustrate this:
In the following section, you’ll learn how to raise errors when using the pd.rename() method.
Raising Errors While Renaming Pandas Columns
By default, the .rename() method will not raise any errors when you include a column that doesn’t exist. This can lead to unexpected errors when you assume that a column has been renamed when it hasn’t.
Let’s see this in action by attempting to rename a column that doesn’t exist:
We can see that by using the errors= parameter, that we can force Python to raise errors when a column label doesn’t exist.
Renaming Multi-index Pandas Columns
The .rename() method also includes an argument to specify which level of a multi-index you want to rename. A common occurrence of multi-index Pandas DataFrames is when working with pivot tables. Let’s take a look at an example. Say we create a Pandas pivot table and only want to rename a column in the first layer.
In the example above, we created a multi-index Pandas DataFrame. The first layer (layer 0) contains the values from our Gender column. By specifying that we want to only use level 0, we can target column labels only in that level. To learn more about Pandas pivot tables, check out my comprehensive guide to Pandas pivot tables.
Add a Prefix or Suffix to Pandas DataFrame Columns
We can also add a prefix or a suffix to all Pandas DataFrame columns by using dedicated methods:
- .add_prefix() will add a prefix to each DataFrame column, and
- .add_suffix() will add a suffix to each DataFrame column
Let’s see how we can use these methods to add a prefix to our DataFrame’s columns:
Adding a suffix would work in the same way, though we would use the .add_suffix() method instead.
Similarly, if we only want to add a suffix to specific columns, we can use a list comprehension. For example, if we wanted to add a suffix to columns that have the word age in them, we can use the following code:
In the example above, we used a list comprehension to apply a transformation conditionally. This allowed us to check for a condition. If the condition was met (in this case, if ‘Age’ was in the column name) then the suffix is added. Otherwise, the column name is left unchanged.
Conclusion
In this post, you learned about the different ways to rename columns in a Pandas DataFrame. You first learned the two main methods for renaming DataFrame columns: using the Pandas .rename() method and using the .columns attribute.
From there, you learned how to rename a single column, both by name and by its position. From there, you learned how to rename multiple columns. You learned how to do this using the .rename() method, as well as list comprehensions. From there, you learned about using mapper functions, both built-in functions, as well as custom lambda functions. Finally, you learned how to rename DataFrames in place, raise errors when columns don’t exist, and how to work with levels in multi-index DataFrames.
Оперирование таблицами pandas #
Считаем таблицу с планетами и выведем типы данных в её столбце.
Количество спутников | Масса | Группа | Кольца | |
---|---|---|---|---|
Название | ||||
Меркурий | 0 | 0.0055 | земная группа | Нет |
Венера | 0 | 0.8150 | земная группа | Нет |
Земля | 1 | 1.0000 | земная группа | Нет |
Марс | 2 | 0.1070 | земная группа | Нет |
Юпитер | 62 | 317.8000 | газовый гигант | Да |
Сатурн | 34 | 95.2000 | газовый гигант | Да |
Уран | 27 | 14.3700 | ледяной гигант | Да |
Нептун | 13 | 17.1500 | ледяной гигант | Да |
Видим, что типы первых столбцов были корректно выведены из таблицы, а вот последние два столбца можно хранить более эффективно.
Во-первых, значение столбца “ Кольца ” булевого характера. Чтобы сразу считать их сразу как булевые, в методе read_csv можно указать какие значения следует интерпретировать в качестве True , а какие в качестве False , параметрами true_values и false_values .
По аналогии с true_values и false_values ещё есть параметр na_values , отвечающий за пропущенные значения.
Количество спутников | Масса | Группа | Кольца | |
---|---|---|---|---|
Название | ||||
Меркурий | 0 | 0.0055 | земная группа | False |
Венера | 0 | 0.8150 | земная группа | False |
Земля | 1 | 1.0000 | земная группа | False |
Марс | 2 | 0.1070 | земная группа | False |
Юпитер | 62 | 317.8000 | газовый гигант | True |
Сатурн | 34 | 95.2000 | газовый гигант | True |
Уран | 27 | 14.3700 | ледяной гигант | True |
Нептун | 13 | 17.1500 | ледяной гигант | True |
Видим, что значения столбца “ Кольца ” автоматически приняли булевый тип.
Во-вторых, значения столбца “ Группа ” принимают одно из трех значений, а хранятся в столбце типа object . Переменные такого характера называют категориальными или номинальными. Для их хранения в pandas эффективнее будет воспользоваться специальным категориальным типом данных.
Для начала продемонстрируем работу метода pandas.Series.astype, который позволяет преобразовать тип данных столбца (или таблицы)
Видим, что метод преобразовал все к типу "category" . Эффективнее, конечно, загрузить таблицу сразу с необходимыми типами данных.
Количество спутников | Масса | Группа | Кольца | |
---|---|---|---|---|
Название | ||||
Меркурий | 0 | 0.005500 | земная группа | False |
Венера | 0 | 0.815000 | земная группа | False |
Земля | 1 | 1.000000 | земная группа | False |
Марс | 2 | 0.107000 | земная группа | False |
Юпитер | 62 | 317.799988 | газовый гигант | True |
Сатурн | 34 | 95.199997 | газовый гигант | True |
Уран | 27 | 14.370000 | ледяной гигант | True |
Нептун | 13 | 17.150000 | ледяной гигант | True |
Названия столбцов#
Иногда может потребоваться переименовать столбцы и метки строк в таблице. Переведем названия столбцов и планет, чтобы продемонстрировать принцип работы метода pd.DataFrame.rename.
number of moons | mass | group | rings | |
---|---|---|---|---|
Название | ||||
Mercury | 0 | 0.005500 | земная группа | False |
Venus | 0 | 0.815000 | земная группа | False |
Earth | 1 | 1.000000 | земная группа | False |
Mars | 2 | 0.107000 | земная группа | False |
jupyter | 62 | 317.799988 | газовый гигант | True |
Saturn | 34 | 95.199997 | газовый гигант | True |
Uranus | 27 | 14.370000 | ледяной гигант | True |
Neptune | 13 | 17.150000 | ледяной гигант | True |
Т.е. в большинстве случаев удобнее всего указать новые названия столбцов и/или новые метки индекса в виде словаря.
Обратите внимание, что по умолчанию метод rename не изменяет названия столбцов на месте, а возвращает копию таблицы с переименованными столбцами. Это стандартное поведение для многих методов pandas : в последнее время разработчики pandas стараются избегать мутирующих методов. Однако если талица очень крупная, то её копирование ради совершения простых операций может оказаться накладным. В таком случае полезным может оказаться метод inplace .
Переименовать название индекса таблицы можно методом pandas.Index.rename
Пропущенные значения#
Большинство методов pandas разработаны таким образом, чтобы они работали с пропущенными значениями.
s1 | s2 | s3 | |
---|---|---|---|
a | 1.0 | -1 | NaN |
b | 2.0 | NaN | NaN |
c | NaN | NaN | NaN |
Например, метод mean вычисляет среднее каждого столбца с численными значениями.