3-3-3-9. Accessing Elements in pandas DataFrames

Let’s see some examples.

Here’s a DataFrame we created in the last video.

We can access the bikes column using the column label,

like this, and use a list of the column labels to access multiple columns.

We can access a row using the row index label,

and the value at a specific row and column like this.

It’s important to know that when accessing individual elements in a DataFrame,

like in this last example,

the column label always comes first,

and then the row label.

If you provide the row label first, you’ll get an error.

We can also modify our DataFrames by adding rows or columns.

Suppose we decided to add a shirts column to our DataFrame, to do this,

we can define our shirts column containing

the quantity for each of the two store rows like this.

This added a new column to the end of our DataFrame.

We can also add new columns using

arithmetic operations on other columns of our DataFrame.

For example, we can create a new column called

suits by computing the sum of the shirts and pants column.

Suppose now, that you opened

a new store and you want to add that as a row on your DataFrame.

To add rows to our DataFrame,

we first have to create a new DataFrame with those rows,

and then append it to the original DataFrame.

Let’s see how this works.

Here is a dictionary of the items in

our new store that we will use to create a DataFrame.

We can now add this row to our store items DataFrame using the append method.

After appending to the DataFrame,

the columns have been placed in alphabetical order.

We can also add new columns to our DataFrame by

selecting data that already exists in our DataFrame.

For example, let’s say you want to stock stores two and three with new watches.

So you decide to add a new column called new watches to your DataFrame,

and say you want the quantity of

these new watches to be the same as the watches already in stock.

Since we only want the stock stores two and three,

we can index them like this.

It is also possible to insert new columns into the DataFrame anywhere we want.

The insert method allows us to specify the location,

label, and data of the column we want to add.

Let’s use this to add a new column called shoes right before the suits column.

The first argument is loc or location, we put five.

So, 0, 1, 2, 3, 4, 5.

So, we actually inserted the shoes column before the watches column.

The second argument is the label,

and the last is the data.

In addition to adding rows and columns,

we can also delete them.

We can use the pop and drop methods to do this.

The pop method allows us to delete columns while

the drop method can be used to delete both rows and columns by using the axis keyword.

Let’s see some examples.

We can delete the new watches column using pop which is used to remove columns.

Now, we will move the watches and shoes columns with drop,

which can be used to remove columns if we set axis to one.

We’ll use that same method to remove

the rows store two and store one by setting axis to zero.

Sometimes, we might need to change the row and column labels.

Let’s change the bikes column label to hats using the rename method.

This takes in a dictionary with original label as keys and the new labels as values.

We can see the bikes has been renamed to hats.

Now, let’s change the row label using the rename method.

We can change the index label of store three to last store like this.

Notice here, we set the index parameter to the dictionary.

Whereas in the previous cell,

we set columns to the dictionary.

We can also set the index to be one of the existing columns in the DataFrame, like this.

Now, we’re using the values in the pants column as our row index labels.

다양한 방식으로 DataFrame의 요소에 액세스할 수 있습니다.

일반적으로 행, 열,

또는 행 및 열 레이블을 사용하여 개별 요소.

몇 가지 예를 살펴보겠습니다.

다음은 지난 비디오에서 만든 DataFrame입니다.

열 레이블을 사용하여 자전거 열에 액세스할 수 있습니다.

이와 같이 열 레이블 목록을 사용하여 여러 열에 액세스합니다.

행 인덱스 레이블을 사용하여 행에 액세스할 수 있습니다.

그리고 이와 같은 특정 행과 열의 값.

DataFrame의 개별 요소에 액세스할 때

이 마지막 예에서와 같이

열 레이블이 항상 먼저 옵니다.

그런 다음 행 레이블.

행 레이블을 먼저 제공하면 오류가 발생합니다.

행이나 열을 추가하여 DataFrame을 수정할 수도 있습니다.

이를 위해 DataFrame에 shirts 열을 추가하기로 결정했다고 가정해 보겠습니다.

다음을 포함하는 셔츠 열을 정의할 수 있습니다.

이와 같이 두 개의 상점 행 각각에 대한 수량입니다.

이것은 DataFrame의 끝에 새 열을 추가했습니다.

다음을 사용하여 새 열을 추가할 수도 있습니다.

DataFrame의 다른 열에 대한 산술 연산.

예를 들어,

셔츠와 바지 열의 합계를 계산하여 양복.

이제 당신이 열었다고 가정해 봅시다.

새 저장소를 만들고 이를 DataFrame의 행으로 추가하려고 합니다.

DataFrame에 행을 추가하려면

먼저 해당 행으로 새 DataFrame을 만들어야 합니다.

그런 다음 원본 DataFrame에 추가합니다.

이것이 어떻게 작동하는지 봅시다.

다음은 항목의 사전입니다.

DataFrame을 만드는 데 사용할 새 저장소입니다.

이제 append 메서드를 사용하여 스토어 항목 DataFrame에 이 행을 추가할 수 있습니다.

DataFrame에 추가한 후,

열은 알파벳 순서로 배치되었습니다.

다음을 통해 DataFrame에 새 열을 추가할 수도 있습니다.

DataFrame에 이미 존재하는 데이터를 선택합니다.

예를 들어, 매장 2개와 3개에 새 시계를 보관하려고 한다고 가정해 보겠습니다.

따라서 DataFrame에 new watch라는 새 열을 추가하기로 결정했습니다.

그리고 당신이 원하는 양

이 새로운 시계는 이미 재고가 있는 시계와 동일합니다.

재고 매장 2개와 3개만 원하기 때문에

이런 식으로 색인을 생성할 수 있습니다.

DataFrame에 원하는 곳에 새 열을 삽입하는 것도 가능합니다.

삽입 방법을 사용하면 위치를 지정할 수 있습니다.

레이블 및 추가하려는 열의 데이터입니다.

이것을 사용하여 정장 열 바로 앞에 신발이라는 새 열을 추가해 보겠습니다.

첫 번째 인수는 loc 또는 위치이며 5를 넣습니다.

따라서 0, 1, 2, 3, 4, 5입니다.

그래서 실제로 시계 열 앞에 신발 열을 삽입했습니다.

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

마지막은 데이터입니다.

행과 열을 추가하는 것 외에도

삭제할 수도 있습니다.

이를 위해 팝 및 드롭 방법을 사용할 수 있습니다.

pop 메서드를 사용하면 열을 삭제할 수 있습니다.

drop 메소드는 axis 키워드를 사용하여 행과 열을 모두 삭제하는 데 사용할 수 있습니다.

몇 가지 예를 살펴보겠습니다.

열을 제거하는 데 사용되는 pop을 사용하여 새 시계 열을 삭제할 수 있습니다.

이제 시계와 신발 기둥을 드롭으로 이동합니다.

축을 1로 설정하면 열을 제거하는 데 사용할 수 있습니다.

동일한 방법을 사용하여

행은 축을 0으로 설정하여 2개를 저장하고 1개를 저장합니다.

경우에 따라 행 및 열 레이블을 변경해야 할 수도 있습니다.

이름 바꾸기 방법을 사용하여 자전거 열 레이블을 모자로 변경해 보겠습니다.

이것은 원래 레이블을 키로 사용하고 새 레이블을 값으로 사용하는 사전을 사용합니다.

우리는 자전거가 모자로 이름이 바뀐 것을 볼 수 있습니다.

이제 이름 바꾸기 방법을 사용하여 행 레이블을 변경해 보겠습니다.

우리는 상점 3의 인덱스 레이블을 이와 같이 마지막 상점으로 변경할 수 있습니다.

여기에서 index 매개변수를 사전으로 설정했습니다.

이전 셀에서,

열을 사전에 설정합니다.

이와 같이 인덱스를 DataFrame의 기존 열 중 하나로 설정할 수도 있습니다.

이제 바지 열의 값을 행 인덱스 레이블로 사용하고 있습니다.

Accessing Elements in Pandas DataFrames

We can access elements in Pandas DataFrames in many different ways. In general, we can access rows, columns, or individual elements of the DataFrame by using the row and column labels. We will use the same store_items DataFrame created in the previous lesson. Let’s see some examples:

Example 1. Access elements using labels

# We print the store_items DataFrame
print(store_items)

# We access rows, columns and elements using labels
print()
print('How many bikes are in each store:\n', store_items[['bikes']])
print()
print('How many bikes and pants are in each store:\n', store_items[['bikes', 'pants']])
print()
print('What items are in Store 1:\n', store_items.loc[['store 1']])
print()
print('How many bikes are in Store 2:', store_items['bikes']['store 2'])
bikesglassespantswatches
store 120NaN3035
store 21550.0510

How many bikes are in each store:

bikes
store 120
store 215

How many bikes and pants are in each store:

bikespants
store 12030
store 2155

What items are in Store 1:

bikesglassespantswatches
store 120NaN3035

How many bikes are in Store 2: 15

It is important to know that when accessing individual elements in a DataFrame, as we did in the last example above, the labels should always be provided with the column label first, i.e. in the form dataframe[column][row]. For example, when retrieving the number bikes in store 2, we first used the column label bikes and then the row label store 2. If you provide the row label first you will get an error.

We can also modify our DataFrames by adding rows or columns. Let’s start by learning how to add new columns to our DataFrames. Let’s suppose we decided to add shirts to the items we have in stock at each store. To do this, we will need to add a new column to our store_items DataFrame indicating how many shirts are in each store. Let’s do that:

Example 2. Add a column to an existing DataFrame

# We add a new column named shirts to our store_items DataFrame indicating the number of
# shirts in stock at each store. We will put 15 shirts in store 1 and 2 shirts in store 2
store_items['shirts'] = [15,2]

# We display the modified DataFrame
store_items
bikesglassespantswatchesshirts
store 120NaN303515
store 21550.05102

We can see that when we add a new column, the new column is added at the end of our DataFrame.

We can also add new columns to our DataFrame by using arithmetic operations between other columns in our DataFrame. Let’s see an example:

Example 3. Add a new column based on the arithmetic operation between existing columns of a DataFrame

# We make a new column called suits by adding the number of shirts and pants
store_items['suits'] = store_items['pants'] + store_items['shirts']

# We display the modified DataFrame
store_items
bikesglassespantswatchesshirtssuits
store 120NaN30351545
store 21550.051027

Suppose now, that you opened a new store and you need to add the number of items in the stock of that new store into your DataFrame. We can do this by adding a new row to the store_items Dataframe. To add rows to our DataFrame we first have to create a new Dataframe and then append it to the original DataFrame. Let’s see how this works

Example 4 a. Create a row to be added to the DataFrame

# We create a dictionary from a list of Python dictionaries that will contain the number of different items at the new store
new_items = [{'bikes': 20, 'pants': 30, 'watches': 35, 'glasses': 4}]

# We create new DataFrame with the new_items and provide and index labeled store 3
new_store = pd.DataFrame(new_items, index = ['store 3'])

# We display the items at the new store
new_store
bikesglassespantswatches
store 32043035

We now add this row to our store_items DataFrame by using the .append() method.

Example 4 b. Append the row to the DataFrame

# We append store 3 to our store_items DataFrame
store_items = store_items.append(new_store)

# We display the modified DataFrame
store_items
bikesglassespantsshirtssuitswatches
store 120NaN3015.045.035
store 21550.052.07.010
store 3204.030NaNNaN35

Notice that by appending a new row to the DataFrame, the columns have been put in alphabetical order.

We can also add new columns of our DataFrame by using only data from particular rows in particular columns. For example, suppose that you want to stock stores 2 and 3 with new watches and you want the quantity of the new watches to be the same as the watches already in stock for those stores. Let’s see how we can do this

Example 5. Add new column that has data from the existing columns

# We add a new column using data from particular rows in the watches column
store_items['new watches'] = store_items['watches'][1:]

# We display the modified DataFrame
store_items
bikesglassespantsshirtssuitswatchesnew watches
store 120NaN3015.045.035NaN
store 21550.052.07.01010.0
store 3204.030NaNNaN3535.0

It is also possible, to insert new columns into the DataFrames anywhere we want. The dataframe.insert(loc,label,data) method allows us to insert a new column in the dataframe at location loc, with the given column label, and given data. Let’s add new column named shoes right before the suits column. Since suits has numerical index value 4 then we will use this value as loc. Let’s see how this works:

Example 6. Add new column at a specific location

# We insert a new column with label shoes right before the column with numerical index 4
store_items.insert(4, 'shoes', [8,5,0])

# we display the modified DataFrame
store_items
bikesglassespantsshirtsshoessuitswatchesnew watches
store 120NaN3015.0845.035NaN
store 21550.052.057.01010.0
store 3204.030NaN0NaN3535.0

Just as we can add rows and columns we can also delete them. To delete rows and columns from our DataFrame we will use the .pop() and .drop() methods. The .pop() method only allows us to delete columns, while the .drop() method can be used to delete both rows and columns by use of the axis keyword. Let’s see some examples

Example 7. Delete one column from a DataFrame

# We remove the new watches column
store_items.pop('new watches')

# we display the modified DataFrame
store_items
bikesglassespantsshirtsshoessuitswatches
store 120NaN3015.0845.035
store 21550.052.057.010
store 3204.030NaN0NaN35

Example 8. Delete multiple columns from a DataFrame

# We remove the watches and shoes columns
store_items = store_items.drop(['watches', 'shoes'], axis = 1)

# we display the modified DataFrame
store_items
bikesglassespantsshirtssuits
store 120NaN3015.045.0
store 21550.052.07.0
store 3204.030NaNNaN

Example 9. Delete rows from a DataFrame

# We remove the store 2 and store 1 rows
store_items = store_items.drop(['store 2', 'store 1'], axis = 0)

# we display the modified DataFrame
store_items
bikesglassespantsshirtssuits
store 3204.030NaNNaN

Sometimes we might need to change the row and column labels. Let’s change the bikes column label to hats using the .rename() method

Example 10. Modify the column label

# We change the column label bikes to hats
store_items = store_items.rename(columns = {'bikes': 'hats'})

# we display the modified DataFrame
store_items
hatsglassespantsshirtssuits
store 3204.030NaNNaN

Now let’s change the row label using the .rename() method again.

Example 11. Modify the row label

# We change the row label from store 3 to last store
store_items = store_items.rename(index = {'store 3': 'last store'})

# we display the modified DataFrame
store_items
hatsglassespantsshirtssuits
last store204.030NaNNaN

You can also change the index to be one of the columns in the DataFrame.

Example 12. Use existing column values as row-index

# We change the row index to be the data in the pants column
store_items = store_items.set_index('pants')

# we display the modified DataFrame
store_items
pantshatsglassesshirtssuits
30204.0NaNNaN
%d