3-3-3-6. Arithmetic Operations on pandas Series

arithmetic operations between Pandas series and single numbers.

Let’s create a new series that holds a grocery list of fruits.

The first argument we pass in is the data,

and the second argument is the index labels.

We can modify the data in fruits by performing basic arithmetic operations.

We can add two to each element in fruits,

subtract two, multiply by two, and divide by two.

We can also apply mathematical functions from

NumPy such as square root to all the elements of a series.

Let’s import NumPy and take a look at our fruit series again.

Using NumPy, we can get the square root of each element like this.

And the exponential of each element,

and each element to the power of two.

Pandas also allows us to apply arithmetic operations on selected items in a series.

Here’s the fruit series again.

We can add two to just the banana’s item, like this.

And let’s subtract two from apples using its numerical index.

We can double the apples and oranges like this,

and divide apples and oranges by two like this.

You can also apply arithmetic operations on a Pandas series of

mixed data types provided that

the arithmetic operation is defined for all data types in the series.

To demonstrate this, let’s go back to our grocery’s list from the previous video,

and let’s multiply this series by two,

since the multiplication operation is defined for both strings and numbers.

This code doesn’t return an error.

Multiplying a string by two simply repeats it.

If you were to apply an operation that was valid for numbers but not strings,

for instance division, you would get an error.

So, when you have mixed data types in your Pandas series,

make sure the arithmetic operations you

use are defined for all the data types in your series.

NumPy 배열에서 했던 것처럼,

Pandas 시리즈에서 요소별 산술 연산을 수행할 수 있습니다.

이번 영상에서는

Pandas 시리즈와 단일 숫자 간의 산술 연산.

과일 식료품 목록이 포함된 새 시리즈를 만들어 보겠습니다.

우리가 전달하는 첫 번째 인수는 데이터입니다.

두 번째 인수는 인덱스 레이블입니다.

기본 산술 연산을 수행하여 과일의 데이터를 수정할 수 있습니다.

과일의 각 요소에 두 개를 추가할 수 있습니다.

2를 빼고 2를 곱하고 2로 나눕니다.

에서 수학 함수를 적용할 수도 있습니다.

시리즈의 모든 요소에 대한 제곱근과 같은 NumPy.

NumPy를 가져와서 과일 시리즈를 다시 살펴보겠습니다.

NumPy를 사용하여 다음과 같이 각 요소의 제곱근을 얻을 수 있습니다.

그리고 각 요소의 지수,

각 요소는 2의 거듭제곱입니다.

Pandas를 사용하면 시리즈에서 선택한 항목에 산술 연산을 적용할 수도 있습니다.

다음은 과일 시리즈입니다.

이렇게 바나나 항목에 두 개를 추가할 수 있습니다.

숫자 인덱스를 사용하여 사과에서 2를 빼보겠습니다.

이렇게 사과와 오렌지를 두 배로 늘릴 수 있습니다.

그리고 사과와 오렌지를 이렇게 둘로 나눕니다.

Pandas 시리즈에 산술 연산을 적용할 수도 있습니다.

제공되는 혼합 데이터 유형

산술 연산은 계열의 모든 데이터 유형에 대해 정의됩니다.

이를 설명하기 위해 이전 비디오의 식료품 목록으로 돌아가 보겠습니다.

이 급수에 2를 곱해 보겠습니다.

곱하기 연산이 문자열과 숫자 모두에 대해 정의되어 있기 때문입니다.

이 코드는 오류를 반환하지 않습니다.

문자열에 2를 곱하면 단순히 반복됩니다.

숫자에는 유효하지만 문자열에는 유효하지 않은 연산을 적용하려는 경우,

예를 들어 나눗셈의 경우 오류가 발생합니다.

따라서 Pandas 시리즈에 혼합 데이터 유형이 있는 경우

산술 연산이

사용은 시리즈의 모든 데이터 유형에 대해 정의됩니다.

Arithmetic Operations on Pandas Series

Just like with NumPy ndarrays, we can perform element-wise arithmetic operations on Pandas Series. In this lesson we will look at arithmetic operations between Pandas Series and single numbers. Let’s create a new Pandas Series that will hold a grocery list of just fruits.

# We create a Pandas Series that stores a grocery list of just fruits
fruits= pd.Series(data = [10, 6, 3,], index = ['apples', 'oranges', 'bananas'])

# We display the fruits Pandas Series
fruits


apples         10 oranges        6 bananas       3 dtype: int64

We can now modify the data in fruits by performing basic arithmetic operations. Let’s see some examples

Example 1. Element-wise basic arithmetic operations

# We print fruits for reference
print('Original grocery list of fruits:\n ', fruits)

# We perform basic element-wise operations using arithmetic symbols
print()
print('fruits + 2:\n', fruits + 2) # We add 2 to each item in fruits
print()
print('fruits - 2:\n', fruits - 2) # We subtract 2 to each item in fruits
print()
print('fruits * 2:\n', fruits * 2) # We multiply each item in fruits by 2
print()
print('fruits / 2:\n', fruits / 2) # We divide each item in fruits by 2
print()


Original grocery list of fruits: apples         10 oranges        6 bananas       3 dtype: int64

fruits + 2: apples         12 oranges        8 bananas       5 dtype: int64

fruits – 2: apples           8 oranges        4 bananas       1 dtype: int64

fruits * 2: apples         20 oranges      12 bananas       6 dtype: int64

fruits / 2: apples           5.0 oranges        3.0 bananas       1.5 dtype: float64

You can also apply mathematical functions from NumPy, such assqrt(x), to all elements of a Pandas Series.

Example 2. Use mathematical functions from NumPy to operate on Series

# We import NumPy as np to be able to use the mathematical functions
import numpy as np

# We print fruits for reference
print('Original grocery list of fruits:\n', fruits)

# We apply different mathematical functions to all elements of fruits
print()
print('EXP(X) = \n', np.exp(fruits))
print()
print('SQRT(X) =\n', np.sqrt(fruits))
print()
print('POW(X,2) =\n',np.power(fruits,2)) # We raise all elements of fruits to the power of 2


Original grocery list of fruits: apples         10 oranges        6 bananas       3 dtype: int64

EXP(X) = apples        22026.465795 oranges         403.428793 bananas          20.085537 dtype: float64

SQRT(X) = apples            3.162278 oranges         2.449490 bananas        1.732051 dtype: float64

POW(X,2) = apples         100 oranges        36 bananas         9 dtype: int64

Pandas also allows us to only apply arithmetic operations on selected items in our fruits grocery list. Let’s see some examples

Example 3. Perform arithmetic operations on selected elements

# We print fruits for reference
print('Original grocery list of fruits:\n ', fruits)
print()

# We add 2 only to the bananas
print('Amount of bananas + 2 = ', fruits['bananas'] + 2)
print()

# We subtract 2 from apples
print('Amount of apples - 2 = ', fruits.iloc[0] - 2)
print()

# We multiply apples and oranges by 2
print('We double the amount of apples and oranges:\n', fruits[['apples', 'oranges']] * 2)
print()

# We divide apples and oranges by 2
print('We half the amount of apples and oranges:\n', fruits.loc[['apples', 'oranges']] / 2)


Original grocery list of fruits: apples         10 oranges        6 bananas       3 dtype: int64

Amount of bananas + 2 = 5

Amount of apples – 2 = 8

We double the amount of apples and oranges: apples         20 oranges      12 dtype: int64

We half the amount of apples and oranges: apples         5.0 oranges      3.0 dtype: float64

You can also apply arithmetic operations on Pandas Series of mixed data type provided that the arithmetic operation is defined for all data types in the Series, otherwise, you will get an error. Let’s see what happens when we multiply our grocery list by 2

Example 4. Perform multiplication on a Series having integer and string elements

# We multiply our grocery list by 2
groceries * 2


eggs                 60 apples             12 milk         YesYes bread        NoNo dtype: object

As we can see, in this case, since we multiplied by 2, Pandas doubles the data of each item including the strings. Pandas can do this because the multiplication operation * is defined both for numbers and strings. If you were to apply an operation that was valid for numbers but not strings, say for instance, / you will get an error. So when you have mixed data types in your Pandas Series make sure the arithmetic operations are valid on all the data types of your elements.