3-3-3-5. Accessing and Deleting Elements in Pandas Series
One great advantage of the series object,
is that it allows us to access data in multiple ways.
One way is accessing elements with their index labels.
This accesses the quantity of eggs using the eggs label in square brackets.
We can get multiple elements by providing a list of index labels.
Another way to access elements is numeric indices,
very similar to how we access elements in NumPy arrays.
Here, we get the quantity of the first item,
eggs, using zero as our index.
Now, let’s get the last element with the index negative one.
And again, we can grab multiple items using a list of numerical indices.
In order to remove any ambiguity from rather we’re referring to an index label,
or a numerical index,
Panda series have two attributes loc,
and iloc, to explicitly state what we mean.
The attribute loc stands for a location,
and it’s used to explicitly state that we’re using a labelled index.
Similarly the attribute iloc,
stands for integer location,
and is used to explicitly state that we are using a numerical index.
Panda series are also mutable like NumPy arrays,
which means we can change the elements of a series after it’s been created.
Let’s change the number of eggs we need to buy from our grocery list.
Let’s see our grocery list again.
We can change the number of eggs from 30 to two by reassigning the element like this.
Now, we can see that the data for eggs has been modified.
We can also delete items from a Panda series using the drop method.
This method removes an element with the given label from the Panda series.
As you can see, apples is no longer included in the series returned by this method.
However, this drops elements from the series out of place.
Meaning, up here, this just returned the modified series,
and didn’t actually change the original one as you can see here.
We can make this happen inplace,
and change the original series by setting the parameter inplace to true.
Now, notice the drop method modified
the actual series instead of returning another series with the modification.
지난 영상에서는
우리는 식료품 목록의 이 판다 시리즈를 만들었습니다.
이제 요소에 액세스하거나 수정하는 방법은 무엇입니까?
시리즈 객체의 큰 장점 중 하나는
여러 가지 방법으로 데이터에 액세스할 수 있다는 것입니다.
한 가지 방법은 인덱스 레이블이 있는 요소에 액세스하는 것입니다.
이것은 대괄호 안에 있는 계란 라벨을 사용하여 계란의 수량에 접근합니다.
인덱스 레이블 목록을 제공하여 여러 요소를 얻을 수 있습니다.
요소에 액세스하는 또 다른 방법은 숫자 인덱스입니다.
NumPy 배열의 요소에 액세스하는 방법과 매우 유사합니다.
여기에서 첫 번째 항목의 수량을 얻습니다.
0을 인덱스로 사용합니다.
이제 인덱스가 음수인 마지막 요소를 가져오겠습니다.
그리고 다시 숫자 인덱스 목록을 사용하여 여러 항목을 가져올 수 있습니다.
모호성을 제거하기 위해 색인 레이블을 참조하고 있습니다.
또는 숫자 인덱스,
팬더 시리즈에는 두 가지 속성이 있습니다.
그리고 iloc은 우리가 의미하는 바를 명시적으로 설명합니다.
속성 loc은 위치를 나타내며,
레이블이 지정된 인덱스를 사용하고 있음을 명시적으로 나타내는 데 사용됩니다.
마찬가지로 속성 iloc,
정수 위치를 나타내며,
숫자 인덱스를 사용하고 있음을 명시적으로 나타내는 데 사용됩니다.
Panda 시리즈도 NumPy 배열처럼 변경 가능합니다.
이는 시리즈가 생성된 후 시리즈의 요소를 변경할 수 있음을 의미합니다.
식료품 목록에서 구입해야 하는 계란의 수를 변경해 보겠습니다.
식료품 목록을 다시 보자.
이와 같이 요소를 재할당하여 알의 수를 30개에서 2개로 변경할 수 있습니다.
이제 계란에 대한 데이터가 수정되었음을 알 수 있습니다.
drop 방법을 사용하여 Panda 시리즈에서 항목을 삭제할 수도 있습니다.
이 메서드는 Panda 시리즈에서 지정된 레이블이 있는 요소를 제거합니다.
보시다시피 사과는 이 메서드가 반환하는 시리즈에 더 이상 포함되지 않습니다.
그러나 이것은 시리즈의 요소를 제자리에서 떨어뜨립니다.
즉, 여기에서 이것은 수정된 시리즈를 반환했습니다.
여기에서 볼 수 있듯이 실제로 원본을 변경하지 않았습니다.
우리는 이 일을 그 자리에서 할 수 있습니다.
inplace 매개변수를 true로 설정하여 원래 시리즈를 변경합니다.
이제 drop 방법이 수정되었음을 확인하십시오.
수정된 다른 시리즈를 반환하는 대신 실제 시리즈.
Accessing and Deleting Elements in Pandas Series
Now let’s look at how we can access or modify elements in a Pandas Series. One great advantage of Pandas Series is that it allows us to access data in many different ways. Elements can be accessed using index labels or numerical indices inside square brackets, [ ], similar to how we access elements in NumPy ndarrays. Since we can use numerical indices, we can use both positive and negative integers to access data from the beginning or from the end of the Series, respectively. Since we can access elements in various ways, in order to remove any ambiguity to whether we are referring to an index label or numerical index, Pandas Series have two attributes, .loc
and .iloc
to explicitly state what we mean. The attribute .loc
stands for location and it is used to explicitly state that we are using a labeled index. Similarly, the attribute .iloc
stands for integer location and it is used to explicitly state that we are using a numerical index. Let’s see some examples:
Example 1. Access elements using index labels
# We access elements in Groceries using index labels: # We use a single index label print('How many eggs do we need to buy:', groceries['eggs']) print() # we can access multiple index labels print('Do we need milk and bread:\n', groceries[['milk', 'bread']]) print() # we use loc to access multiple index labels print('How many eggs and apples do we need to buy:\n', groceries.loc[['eggs', 'apples']]) print() # We access elements in Groceries using numerical indices: # we use multiple numerical indices print('How many eggs and apples do we need to buy:\n', groceries[[0, 1]]) print() # We use a negative numerical index print('Do we need bread:\n', groceries[[-1]]) print() # We use a single numerical index print('How many eggs do we need to buy:', groceries[0]) print() # we use iloc to access multiple numerical indices print('Do we need milk and bread:\n', groceries.iloc[[2, 3]])
How many eggs do we need to buy: 30
Do we need milk and bread: milk Yes bread No dtype: object
How many eggs and apples do we need to buy: eggs 30 apples 6 dtype: object
How many eggs and apples do we need to buy: eggs 30 apples 6 dtype: object
Do we need bread: bread No dtype: object
How many eggs do we need to buy: 30
Do we need milk and bread: milk Yes bread No dtype: object
Pandas Series are also mutable like NumPy ndarrays, which means we can change the elements of a Pandas Series after it has been created. For example, let’s change the number of eggs we need to buy from our grocery list
Example 2. Mutate elements using index labels
# We display the original grocery list print('Original Grocery List:\n', groceries) # We change the number of eggs to 2 groceries['eggs'] = 2 # We display the changed grocery list print() print('Modified Grocery List:\n', groceries)
Original Grocery List: eggs 30 apples 6 milk Yes bread No dtype: object
Modified Grocery List: eggs 2 apples 6 milk Yes bread No dtype: object
We can also delete items from a Pandas Series by using the .drop()
method. The Series.drop(label)
method removes the given label
from the given Series
. We should note that the Series.drop(label)
method drops elements from the Series out-of-place, meaning that it doesn’t change the original Series being modified. Let’s see how this works:
Example 3. Delete elements out-of-place using drop()
# We display the original grocery list print('Original Grocery List:\n', groceries) # We remove apples from our grocery list. The drop function removes elements out of place print() print('We remove apples (out of place):\n', groceries.drop('apples')) # When we remove elements out of place the original Series remains intact. To see this # we display our grocery list again print() print('Grocery List after removing apples out of place:\n', groceries)
Original Grocery List: eggs 30 apples 6 milk Yes bread No dtype: object
We remove apples (out of place): eggs 30 milk Yes bread No dtype: object
Grocery List after removing apples out of place: eggs 30 apples 6 milk Yes bread No dtype: object
We can delete items from a Pandas Series in place by setting the keyword inplace
to True
in the .drop()
method. Let’s see an example:
Example 4. Delete elements in-place using drop()
# We display the original grocery list print('Original Grocery List:\n', groceries) # We remove apples from our grocery list in place by setting the inplace keyword to True groceries.drop('apples', inplace = True) # When we remove elements in place the original Series its modified. To see this # we display our grocery list again print() print('Grocery List after removing apples in place:\n', groceries)
Original Grocery List: eggs 30 apples 6 milk Yes bread No dtype: object
Grocery List after removing apples in place: eggs 30 milk Yes bread No dtype: object
Additional Reading – Pandas Series Documentation
Refer to the list of available functions in the following two sections:
댓글을 달려면 로그인해야 합니다.