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

от admin

Pandas Sum() – Sum each Column and Row in Pandas DataFrame

Pandas sum(): We will see in this tutorial how to use the sum() function for a column or row in a Pandas dataframe.

Introduction

A pandas dataframe is a two-dimensional tabular data structure that can be modified in size with labeled axes that are commonly referred to as row and column labels, with different arithmetic operations aligned with the row and column labels.

The Pandas library, available on python, allows to import data and to make quick analysis on loaded data.

In this tutorial, we will see how to use the sum() function present in the pandas library. This pandas function allows to return the sum of the values according to the axis requested in parameter. We will see the following points:

  • Use the sum() function to sum the values on the index axis (the rows)
  • Use the sum() function to sum the values on the columns axis
  • Sum the values with a multi-level index
  • Sum the values on a Series type

To illustrate these different points, we will use the following pandas dataframe:

This dataframe contains the different incomes generated per month and per day.

Pandas Dataframe sum() function

Pandas sum() Syntax

The sum() function is used to sum the values on a given axis. Its syntax is the following:

The function can take 6 parameters:

Name Description Type Default Value Required
axis The axis to apply the function ( 0=index,1=columns) Yes
skipna Exclude NA / NULL values True No
level If the axis is a MultiIndex (hierarchical), count along a particular level, reducing to a series. int or level name None No
numeric_only Include only float, int, boolean columns. If none, will try to use everything, then use only numeric data. Not implemented for the series. Boolean True No
min_count The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. int 0 No
** kwargs Additional arguments to be passed to the function. No

Sum each Column in Pandas DataFrame

In order to sum each column of the DataFrame, you can use the axis parameter in this way:

You can apply this code to our previously created dataframe:

We obtain the sum of the income A and the sum of the income B on the last quarter.

Sum each Row in Pandas DataFrame

In order to sum each row of the DataFrame, you can use the axis=1 as follows:

You can apply this code to our previously created dataframe:

In our example, this allows us to sum the income A and B for each row.

Multi Level Index Sum

If your dataframe has a multi-level index, you can tell pandas which index you want to sum across.

Our example dataframe contains 2 levels. To sum according to the first level, you can use this:

To sum from the second level, you can do this:

Summing a Series

You can also use the pandas sum() function on a series :

Conclusion

In this tutorial, we have how to simply use the sum() function of the pandas library. This function is very useful to quickly analyze the data and make quick calculations on the columns or rows of our dataframe.

If you have any questions about its use, don’t hesitate to ask me in comments, I’ll be happy to answer them.

See you soon for new tutorials.

I’m a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming 🙂

Pandas Sum: Add Dataframe Columns and Rows

Pandas Sum Add Values in Dataframe - Cover Image

In this tutorial, you’ll learn how use Pandas to calculate a sum, including how to add up dataframe columns and rows. Being able to add up values to calculate either column totals or row totals allows you to generate some helpful summary statistics.

By the end of this tutorial, you’ll have learned how to:

  • Calculate the Sum of a Pandas Dataframe Column
  • Calculate the Sum of a Pandas Dataframe Row
  • Add Pandas Dataframe Columns Together
  • Add Pandas Dataframe Columns That Meet a Condition
  • Calculate the Sum of a Pandas GroupBy Dataframe

Quick Answer: Use Pandas .sum() To Add Dataframe Columns and Rows

How to add values Description Example
Column-wise Add all numeric values in a Pandas column or a dataframe’s columns df[‘column name’].sum()
Row-wise Add all numeric values in a Pandas row df.sum(axis=1)
Specific Columns Add values of specific columns df[‘column 1’] + df[‘column 2’]

How to use the Pandas sum method to add values in different ways

Table of Contents

Loading a Sample Pandas Dataframe

If you want to follow along with the tutorial line by line, copy the code below. This code loads a sample Pandas Dataframe that we’ll reference throughout the tutorial. If you have your own data, feel free to use that follow along, but your results will vary.

We can see that we have four columns: 1 that contains the name of a salesperson and three that contain the sales values of each salesperson.

In the next section, you’ll learn how to use Pandas to add up all the values in a dataframe column.

Calculate the Sum of a Pandas Dataframe Column

A common task you may need to do is add up all the values in a Pandas Dataframe column. Thankfully, Pandas makes this very easy with the sum method. We can apply this method to either a Pandas series (meaning, a column) or an entire dataframe.

Let’s start by learning how to how to add up all the values in a Pandas column:

Similarly, we can calculate the sum of all columns in a Pandas Dataframe. We can do this by simply applying the sum method on the entire dataframe.

Let’s give this a shot:

This returns a Pandas series that easily query, if we wanted to return the sum of a particular column. By default, Pandas will only add up numeric columns, meaning that we don’t add up our Name column.

In the next section, you’ll learn how to calculate the sum of a Pandas Dataframe row.

Calculate the Sum of a Pandas Dataframe Row

In many cases, you’ll want to add up values across rows in a Pandas Dataframe. Similar to the example above, we can make use of the .sum method. By default, Pandas will apply an axis=0 argument, which will add up values index-wise. If we can change this to axis=1 , values will be added column-wise.

Let’s see how we can add up values across rows in Pandas:

You may be wondering why we apply the numeric_only=True argument here. In future versions of Pandas, a TypeError will be thrown if non-numeric columns are included.

What if we wanted to assign an index to make the rows easier to tell apart? We can do this using the Pandas set_index method. Let’s see what this looks like:

This is much cleaner result that allows us to better see the row’s identifier, which in this case is the name of the salesperson.

In the next section, you’ll learn how to just add some columns of a Pandas Dataframe together.

Add Pandas Dataframe Columns Together

Pandas makes it easy to add different columns together, selectively. Say we only wanted to add two columns together row-wise, rather than all of them, we can simply add the columns directly. The benefit of this approach is that we can assign a new column that stores these values.

Let’s see what this looks like:

We can see that the we’ve created a new column that stores the sum of two of our columns. A great thing about this operation is that its vectorized, meaning that its very fast and takes advantage of the power of Pandas.

In the next section, you’ll learn how to add dataframe columns conditionally.

Add Pandas Dataframe Columns That Meet a Condition

There may be times when you want to add multiple columns in a dataframe, but not all of them. We can do this by adding Pandas columns conditionally, with the help of a list comprehension.

For this example, let’s modify our dataframe to include an additional numerical column:

Now, when we’re adding the values of our rows, it may not make sense to include the last column. Say, we only wanted to include the columns that include the word Sales. What we can do is create a list comprehension that checks if the word Sales exists in a column or not.

Let’s see how we can do this:

You can learn more about how to do this in this tutorial, by learning how to iterate over columns and checking for a condition. In order to do this, we’ll first use Pandas to get our DataFrame’s columns as a list.

Now that we have our columns selected, we can use the axis=1 argument and add up only the columns that contain Sales. Let’s see what this looks like:

This way, we can safely add up values across columns row-wise without adding in columns that we don’t want to include.

In the next section, you’ll learn how to calculate the sum of a Pandas Dataframe when data are grouped using groupby .

Calculate the Sum of a Pandas GroupBy Dataframe

In this final section, you’ll learn how to calculate the sum of a Pandas Dataframe when grouping data using the groupby method. For this, we’ll modify our dataframe to include a column to a salesperson’s gender. This can allow us to group the data by gender and calculating totals by gender.

We can now group our data using the group by method, in order to group it by gender. To learn more about how to group data with the groupby method, check out my video here:

Let’s group our data and add all the numeric columns:

We can see that first grouping our data by Gender and then adding the values in the dataframe returns a column-wise sum based on the groupings of Gender.

Conclusion

In this tutorial, you learned how to use the Pandas sum method to calculate sums across dataframes. You learned how to add values row-wise and column-wise. You also learned how add columns conditionally and how to add values in a grouped Pandas Dataframe.

To learn more about the Pandas sum function, check out the official documentation here.

Pandas Dataframe.sum() method – Tutorial & Examples

In this article we will discuss how to use the sum() function of Dataframe to sum the values in a Dataframe along a different axis. We will also discuss all the parameters of the sum() function in detail.

In Pandas, the Dataframe provides a member function sum(), that can be used to get the sum of values in a Dataframe along the requested axis i.e. the sum of values along with columns or along rows in the Dataframe.

Let’s know more about this function,

Syntax of Dataframe.sum()

Parameters:

  • axis: The axis along which the sum of values will be calculated.
    • 0: To get the sum of values along the index/rows
    • 1: To get the sum of values along the columns
    • If True then skip NaNs while calculating the sum.
    • If the axis is Multi-Index, then add items in a given level only
    • If True then include only int, float or Boolean.
    • Add items only when non-NaN values are equal to or more than min_count.

    Returns:

    • If no level information is provided or dataframe has only one index, then sum() function returns a series containing the sum of values along the given axis. Whereas, if dataframe is a Multi-Index dataframe and level information is provided then sum() function returns a Dataframe.

    Let’s understand this with some examples,

    Read More:

    Example 1: Pandas Dataframe.sum() without any parameter

    Suppose we have a Dataframe,

    If we call the sum() function on this Dataframe without any axis parameter, then by default axis value will be 0 and it returns a Series containing the sum of values along the index axis i.e. it will add the values in each column and returns a Series of these values,

    As values were summed up along the index axis i.e. along the rows. So, it returned a Series object where each value in the series represents the sum of values in a column and its index contains the corresponding column Name.

    Example 2: Dataframe.sum() with axis value 1

    If we pass the axis value 1, then it returns a Series containing the sum of values along the column axis i.e. axis 1. It will add the values in each row and returns a Series of these values,

    As values were summed up along the axis 1 i.e. along with the columns. It returned a Series object where each value in the series represents the sum of values in a row and its index contains the corresponding row Index Label of Dataframe.

    Example 3: Dataframe.sum() without skipping NaN

    The default value of skipna parameter is True, so if we call the sum() function without skipna parameter then it skips all the NaN values by default. But if you don’t want to skip NaNs then we can pass the skipna parameter as False i.e.

    It returned a Series containing sum of values in columns. But for any column if it contains the NaN then sum() returned total as NaN for that particular column. Like in above example ‘Feb’ & ‘March’ columns have NaN values and skipna is False, therefore the sum of values in these columns is NaN too.

    Example 4: Dataframe.sum() with min_count

    If min_count is provided then it will sum the values in a column or a row only if the minimum non-NaN values are equal or greater than the min_count value. For example,

    Here, columns ‘Feb’ & ‘March’ in dataframe have only 6 non-NaN values, so they didn’t satisfy our criteria of minimum non-NaN values. Therefore the sum of value in these columns was not calculated and NaN is used instead of that,

    Ecample 5: Dataframe.sum() with a specific level in Multi-Index Dataframe

    Suppose we have a Multi-Index Dataframe,

    Now we if we provide the level parameter then add the values for that particular level only. For example,

    Моя шпаргалка по pandas

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

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

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

    1. Подготовка к работе

    Если вы хотите самостоятельно опробовать то, о чём тут пойдёт речь, загрузите набор данных Anime Recommendations Database с Kaggle. Распакуйте его и поместите в ту же папку, где находится ваш Jupyter Notebook (далее — блокнот).

    Теперь выполните следующие команды.

    После этого у вас должна появиться возможность воспроизвести то, что я покажу в следующих разделах этого материала.

    2. Импорт данных

    ▍Загрузка CSV-данных

    Здесь я хочу рассказать о преобразовании CSV-данных непосредственно в датафреймы (в объекты Dataframe). Иногда при загрузке данных формата CSV нужно указывать их кодировку (например, это может выглядеть как encoding=’ISO-8859–1′ ). Это — первое, что стоит попробовать сделать в том случае, если оказывается, что после загрузки данных датафрейм содержит нечитаемые символы.

    Загруженные CSV-данные

    Существует похожая функция для загрузки данных из Excel-файлов — pd.read_excel .

    ▍Создание датафрейма из данных, введённых вручную

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

    Данные, введённые вручную

    ▍Копирование датафрейма

    Копирование датафреймов может пригодиться в ситуациях, когда требуется внести в данные изменения, но при этом надо и сохранить оригинал. Если датафреймы нужно копировать, то рекомендуется делать это сразу после их загрузки.

    Копия датафрейма

    3. Экспорт данных

    ▍Экспорт в формат CSV

    При экспорте данных они сохраняются в той же папке, где находится блокнот. Ниже показан пример сохранения первых 10 строк датафрейма, но то, что именно сохранять, зависит от конкретной задачи.

    Экспортировать данные в виде Excel-файлов можно с помощью функции df.to_excel .

    4. Просмотр и исследование данных

    ▍Получение n записей из начала или конца датафрейма

    Сначала поговорим о выводе первых n элементов датафрейма. Я часто вывожу некоторое количество элементов из начала датафрейма где-нибудь в блокноте. Это позволяет мне удобно обращаться к этим данным в том случае, если я забуду о том, что именно находится в датафрейме. Похожую роль играет и вывод нескольких последних элементов.

    Данные из начала датафрейма

    Данные из конца датафрейма

    ▍Подсчёт количества строк в датафрейме

    Функция len(), которую я тут покажу, не входит в состав pandas . Но она хорошо подходит для подсчёта количества строк датафреймов. Результаты её работы можно сохранить в переменной и воспользоваться ими там, где они нужны.

    ▍Подсчёт количества уникальных значений в столбце

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

    ▍Получение сведений о датафрейме

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

    Сведения о датафрейме

    Есть ещё одна функция, похожая на df.info — df.dtypes . Она лишь выводит сведения о типах данных столбцов.

    ▍Вывод статистических сведений о датафрейме

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

    Статистические сведения о датафрейме

    ▍Подсчёт количества значений

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

    Подсчёт количества элементов в столбце

    5. Извлечение информации из датафреймов

    ▍Создание списка или объекта Series на основе значений столбца

    Это может пригодиться в тех случаях, когда требуется извлекать значения столбцов в переменные x и y для обучения модели. Здесь применимы следующие команды:

    Результаты работы команды anime[‘genre’].tolist()

    Результаты работы команды anime[‘genre’]

    ▍Получение списка значений из индекса

    Поговорим о получении списков значений из индекса. Обратите внимание на то, что я здесь использовал датафрейм anime_modified , так как его индексные значения выглядят интереснее.

    Результаты выполнения команды

    ▍Получение списка значений столбцов

    Вот команда, которая позволяет получить список значений столбцов:

    Результаты выполнения команды

    6. Добавление данных в датафрейм и удаление их из него

    ▍Присоединение к датафрейму нового столбца с заданным значением

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

    ▍Создание нового датафрейма из подмножества столбцов

    Это может пригодиться в том случае, если требуется сохранить в новом датафрейме несколько столбцов огромного датафрейма, но при этом не хочется выписывать имена столбцов, которые нужно удалить.

    Результат выполнения команды

    ▍Удаление заданных столбцов

    Этот приём может оказаться полезным в том случае, если из датафрейма нужно удалить лишь несколько столбцов. Если удалять нужно много столбцов, то эта задача может оказаться довольно-таки утомительной, поэтому тут я предпочитаю пользоваться возможностью, описанной в предыдущем разделе.

    Результаты выполнения команды

    ▍Добавление в датафрейм строки с суммой значений из других строк

    Для демонстрации этого примера самостоятельно создадим небольшой датафрейм, с которым удобно работать. Самое интересное здесь — это конструкция df.sum(axis=0) , которая позволяет получать суммы значений из различных строк.

    Результат выполнения команды

    Команда вида df.sum(axis=1) позволяет суммировать значения в столбцах.

    Похожий механизм применим и для расчёта средних значений. Например — df.mean(axis=0) .

    7. Комбинирование датафреймов

    ▍Конкатенация двух датафреймов

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

    В данном примере мы сначала разделяем датафрейм на две части, а потом снова объединяем эти части:

    Датафрейм df1

    Датафрейм df2

    Датафрейм, объединяющий df1 и df2

    ▍Слияние датафреймов

    Функция df.merge , которую мы тут рассмотрим, похожа на левое соединение SQL. Она применяется тогда, когда два датафрейма нужно объединить по некоему столбцу.

    Результаты выполнения команды

    8. Фильтрация

    ▍Получение строк с нужными индексными значениями

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

    Результаты выполнения команды

    ▍Получение строк по числовым индексам

    Эта методика отличается от той, которая описана в предыдущем разделе. При использовании функции df.iloc первой строке назначается индекс 0 , второй — индекс 1 , и так далее. Такие индексы назначаются строкам даже в том случае, если датафрейм был модифицирован и в его индексном столбце используются строковые значения.

    Следующая конструкция позволяет выбрать три первых строки датафрейма:

    Результаты выполнения команды

    ▍Получение строк по заданным значениям столбцов

    Для получения строк датафрейма в ситуации, когда имеется список значений столбцов, можно воспользоваться следующей командой:

    Результаты выполнения команды

    Если нас интересует единственное значение — можно воспользоваться такой конструкцией:

    ▍Получение среза датафрейма

    Эта техника напоминает получение среза списка. А именно, речь идёт о получении фрагмента датафрейма, содержащего строки, соответствующие заданной конфигурации индексов.

    Результаты выполнения команды

    ▍Фильтрация по значению

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

    Результаты выполнения команды

    9. Сортировка

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

    Результаты выполнения команды

    10. Агрегирование

    ▍Функция df.groupby и подсчёт количества записей

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

    Результаты выполнения команды

    ▍Функция df.groupby и агрегирование столбцов различными способами

    Обратите внимание на то, что здесь используется reset_index() . В противном случае столбец type становится индексным столбцом. В большинстве случаев я рекомендую делать то же самое.

    ▍Создание сводной таблицы

    Для того чтобы извлечь из датафрейма некие данные, нет ничего лучше, чем сводная таблица. Обратите внимание на то, что здесь я серьёзно отфильтровал датафрейм, что ускорило создание сводной таблицы.

    Результаты выполнения команды

    11. Очистка данных

    ▍Запись в ячейки, содержащие значение NaN, какого-то другого значения

    Здесь мы поговорим о записи значения 0 в ячейки, содержащие значение NaN . В этом примере мы создаём такую же сводную таблицу, как и ранее, но без использования fill_value=0 . А затем используем функцию fillna(0) для замены значений NaN на 0 .

    Таблица, содержащая значения NaN

    Результаты замены значений NaN на 0

    12. Другие полезные возможности

    ▍Отбор случайных образцов из набора данных

    Я использую функцию df.sample каждый раз, когда мне нужно получить небольшой случайный набор строк из большого датафрейма. Если используется параметр frac=1 , то функция позволяет получить аналог исходного датафрейма, строки которого будут перемешаны.

    Результаты выполнения команды

    ▍Перебор строк датафрейма

    Следующая конструкция позволяет перебирать строки датафрейма:

    Результаты выполнения команды

    ▍Борьба с ошибкой IOPub data rate exceeded

    Если вы сталкиваетесь с ошибкой IOPub data rate exceeded — попробуйте, при запуске Jupyter Notebook, воспользоваться следующей командой:

    Итоги

    Здесь я рассказал о некоторых полезных приёмах использования pandas в среде Jupyter Notebook. Надеюсь, моя шпаргалка вам пригодится.

    Уважаемые читатели! Есть ли какие-нибудь возможности pandas , без которых вы не представляете своей повседневной работы?

    Читать:
    Монитор производительности advanced systemcare диск 100 что делать

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