Monday, 4 December 2023

Pandas: iloc: Access the DataFrame rows using index position

In this post, I am going to explain how to access the DataFrame rows using index position.

 

I am going to use below dataset to demonstrate the examples.

       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      81
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

As per the above data set,

a.   row with index 0 point to the person ‘Krishna’ details

b.   Row with 1 point to the person ‘Sailu’ details etc.,

 

How to access a row at index 0?

Using df.iloc[index_location], we can access the row at index 0.

row_at_1st_position = df.iloc[0]

How to access multiple rows at a time?

By passing the list of index locations to the iloc accessor, we can access multiple rows.

rows_at_2nd_4th_positions = df.iloc[[2, 4]]

Above statement extract the rows at indexes 2nd  and 4th positions.

 

You will get ‘IndexError’, when trying to access the index which is out of bounds.

 

Find the below working application.

 

iloc_hello_world.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [81, 76, 67, 100, 87, 89]}

df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

row_at_1st_position = df.iloc[0]
row_at_2nd_position = df.iloc[1]
print('\nrow_at_1st_position : \n', row_at_1st_position)
print('\nrow_at_2nd_position : \n', row_at_2nd_position)

rows_at_2nd_4th_positions = df.iloc[[2, 4]]
print('\nrows_at_2nd_4th_positions: \n', rows_at_2nd_4th_positions)

try:
    print('\nTrying to access the element at index 10')
    print(df.iloc[10])
except IndexError as e:
    print(e)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      81
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

row_at_1st_position : 
 Name        Krishna
Age              34
City      Bangalore
Gender         Male
Rating           81
Name: 0, dtype: object

row_at_2nd_position : 
 Name          Sailu
Age              35
City      Hyderabad
Gender       Female
Rating           76
Name: 1, dtype: object

rows_at_2nd_4th_positions: 
        Name  Age       City Gender  Rating
2      Joel   29  Hyderabad   Male      67
4  Jitendra   52  Bangalore   Male      87
Trying to access the element at index 10
single positional indexer is out-of-bounds

Following are the common use cases of iloc accessor.

 

a.   Accessing Rows and Columns

b.   Slicing

c.    Assigning values

 

Accessing rows and columns

In Pandas, both row and column indexes will start from 0.

 

Example 1: Access a single row by its integer index

df.iloc[row_index_1]

 

Example 2: Access multiple rows by their integer indices

df.iloc[[row_index_1, row_index_2]]

 

Example 3: Access specific column of the row

df.iloc[row_index_1, column_index_1]

 

Example 4: Access specific columns of the row

df.iloc[row_index_1, [column_index_1, column_index_2]]

 

Example 5: Access multiple rows and columns

df.iloc[[row_index_1, row_index_2], [column_index_1, column_index_2]]

 

access_rows_columns.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [81, 76, 67, 100, 87, 89]}

df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

row_index_1 = 2
row_index_2 = 4

column_index_1 = 0
column_index_2 = 2

# Access a single row by its integer index
result = df.iloc[row_index_1]
print('\nAccess a single row by its integer index :\n', result)

# Access multiple rows by their integer indices
result = df.iloc[[row_index_1, row_index_2]]
print('\nAccess multiple rows by their integer indices :\n', result)

# Access specific column of the row
result = df.iloc[row_index_1, column_index_1]
print('\nAccess specific column of the row :\n', result)

# Access specific columns of the row
result = df.iloc[row_index_1, [column_index_1, column_index_2]]
print('\nAccess specific columns of the row :\n', result)

# Access multiple rows and columns
result = df.iloc[[row_index_1, row_index_2], [column_index_1, column_index_2]]
print('\nAccess multiple rows and columns :\n', result)

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      81
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

Access a single row by its integer index :
 Name           Joel
Age              29
City      Hyderabad
Gender         Male
Rating           67
Name: 2, dtype: object

Access multiple rows by their integer indices :
        Name  Age       City Gender  Rating
2      Joel   29  Hyderabad   Male      67
4  Jitendra   52  Bangalore   Male      87

Access specific column of the row :
 Joel

Access specific columns of the row :
 Name         Joel
City    Hyderabad
Name: 2, dtype: object

Access multiple rows and columns :
        Name       City
2      Joel  Hyderabad
4  Jitendra  Bangalore

Slicing

Example 1: Slice rows based on integer indices

df.iloc[row_start_index:row_end_index]

 

Example 2:  Access all the rows from starting to row_end_index (end index is exclusive)

df.iloc[:row_end_index]

 

Example 3: Access all the rows from row_start_index to end

df.iloc[row_start_index:]

 

Example 4: Slice rows based on integer indices and a step of step_count

df.iloc[row_start_index:row_end_index:step_count]

 

Example 5: Slice rows and select specific columns

df.iloc[row_start_index:row_end_index, column_start_index:column_end_index]

 

Example 6: Access all rows for specific column

df.iloc[:, column_index]

 

Example 7: Access all rows for specific columns

df.iloc[:, [column_index_1, column_index_2]]

 

slicing.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [81, 76, 67, 100, 87, 89]}

df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

row_start_index = 1
row_end_index = 5
step_count = 2
column_start_index = 0
column_end_index = 3
column_index = 0
column_index_1 = 0
column_index_2 = 2

# Slice rows based on integer indices
result = df.iloc[row_start_index:row_end_index]
print('\nSlice rows based on integer indices\n', result)

# Access all the rows from starting to row_end_index
result = df.iloc[:row_end_index]
print('\nAccess all the rows from starting to row_end_index\n', result)

# Access all the rows from row_start_index to end
result = df.iloc[row_start_index:]
print('\nAccess all the rows from row_start_index to end\n', result)

# Slice rows based on integer indices and a step of step_count
result = df.iloc[row_start_index:row_end_index:step_count]
print('\nSlice rows based on integer indices and a step of step_count\n', result)

# Slice rows and select specific columns
result = df.iloc[row_start_index:row_end_index, column_start_index:column_end_index]
print('\nSlice rows and select specific columns\n', result)

# Access all rows for specific column
result = df.iloc[:, column_index]
print('\nAccess all rows for specific column\n', result)

# Access all rows for specific columns
result = df.iloc[:, [column_index_1, column_index_2]]
print('\nAccess all rows for specific columns\n', result)

 

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      81
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

Slice rows based on integer indices
        Name  Age       City  Gender  Rating
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87

Access all the rows from starting to row_end_index
        Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      81
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87

Access all the rows from row_start_index to end
        Name  Age       City  Gender  Rating
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

Slice rows based on integer indices and a step of step_count
     Name  Age       City  Gender  Rating
1  Sailu   35  Hyderabad  Female      76
3  Chamu   35    Chennai  Female     100

Slice rows and select specific columns
        Name  Age       City
1     Sailu   35  Hyderabad
2      Joel   29  Hyderabad
3     Chamu   35    Chennai
4  Jitendra   52  Bangalore

Access all rows for specific column
 0     Krishna
1       Sailu
2        Joel
3       Chamu
4    Jitendra
5         Raj
Name: Name, dtype: object

Access all rows for specific columns
        Name       City
0   Krishna  Bangalore
1     Sailu  Hyderabad
2      Joel  Hyderabad
3     Chamu    Chennai
4  Jitendra  Bangalore
5       Raj    Chennai

 

Assigning Values

Example 1: Assign a value to a specific cell

df.iloc[row_index, column_index] = 'Harika'

 

Example 2: Assign a value to multiple cells based on a condition

df.iloc[df['City'] == 'Hyderabad', column_index] = 'Mumbai'

 

assign_values.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [81, 76, 67, 100, 87, 89]}

df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

row_index = 1
column_index = 0
# Assign a value to a specific cell
print('\nSet the Name of row index 1 to Harika')
df.iloc[row_index, column_index] = 'Harika'
print(df)

# Assign a value to multiple cells based on a condition
column_index = 2
print('\nSet the city of all the people living in Hyderabad to Mumbai')
df.iloc[df['City'] == 'Hyderabad', column_index] = 'Mumbai'
print(df)

 

Output

Original DataFrame
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      81
1     Sailu   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

Set the Name of row index 1 to Harika
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      81
1    Harika   35  Hyderabad  Female      76
2      Joel   29  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

Set the city of all the people living in Hyderabad to Mumbai
       Name  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      81
1    Harika   35     Mumbai  Female      76
2      Joel   29     Mumbai    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      87
5       Raj   34    Chennai    Male      89

 

 

 

Previous                                                 Next                                                 Home

Latency vs Response time

Latency and Response Time are two different ways to measure how well a system works.

Latency

Latency is the time it takes for information to travel from one place to another. We usually measure it in milliseconds.

 

It mostly deals with how fast data moves through networks and communication systems. If we want to make it faster, we often need to make changes to the network or the way we communicate. If there's a high latency, it could mean there are problems with the network.

 

Response Time

Response time is the total time it takes to finish a task. This includes both  processing time  and any waiting time (latency). We measure it in milliseconds or seconds.

 

Making response time better means looking at the whole system, especially when we have many small parts (microservices) working together.

 

So, when we want to make a system work better, we might need to look at latency for speed in data movement and response time for overall task completion.

 

 


As you see above diagram.

Latency = request travel time + response travel time

             = 1 + 5

             = 6

 

Response time = Latency + Processing time

                      = 6 + 2

                      = 8

 

 

In summary, Low latency and fast response times are crucial for handling increased user load and ensuring smooth microservice interactions.

                                                             System Design Questions

Sunday, 3 December 2023

Redundant Array of Independent Disks (RAID)

RAID, stands for "Redundant Array of Independent Disks," is a way of using many disks together to do things better. It puts data on different disks, making things faster because it can do many things at once. Even if one disk fails, the information on the other disks can be used to put the lost data back together.

 


The most common RAID types are

1. RAID 0 (striping),

2. RAID 1 (mirroring) and its variants,

3. RAID 5 (distributed parity), and

4. RAID 6 (dual parity)

 

RAID 0 (Striping)

Data striping is a way of spreading information across many disks or storage gadgets. It make data accessing faster because it lets different disks be used at the same time.

 

For instance, assume your computer having 4 disks, and imagine a file called a.txt divided into 9 parts (a1, a2, a3, a4, a5, a6, a7, a8, and a9). These parts would be stored one after another on all four disks. You can think of it like this in the diagram below.



In RAID-0, there's no backup for the data, so if one disk fails, you can't get the whole file back. RAID-0 makes data go faster because it reads and writes at a speed that's n times as high as a single drive, but with no data redundancy.

 

RAID 1

RAID 1 maintains exact copy of the data on two or more disks. In general, a mirrored image is a classic example of Raid 1. A mirrored image contain two disks, each disk contain same content. This setup doesn't do any fancy things like parity or spreading data across multiple disks. Instead, it simply copies the same data onto all the disks in the group. The size of the whole setup can only be as big as the smallest disk in it.

 


 

RAID-1 keeps working as long as there is at least one working drive in the group.

 

RAID 4 (Block level striping and parity disk)

RAID 4 consists of block-level striping with a dedicated parity disk.

 

 

RAID 4 is good at quickly finding and reading data from random places. However, it's not so fast at writing data randomly because it has to put all the parity information on one disk.

 

To understand how a parity block gets back lost data, think of having three hard disks. Two of them store data, and the third stores the parity. The parity block is made by doing simple X-OR operations on the data blocks. You can see this in the table below.

 

Data block on Disk1

Data block on Disk2

Parity block on Disk3

1010

0101

1111

1111

1100

0011

0000

1011

1011

0011

1101

1110

 

Parity for the first row data blocks

1010 (X-OR) 0101 = 1111

 

Parity for the second row data blocks

1111 (X-OR) 1100 = 0011

 

Parity for the third row data blocks

0000 (X-OR) 1011 = 1011

 

Parity for the fourth row data blocks

0011 (X-OR) 1101 = 1110

 

Scenario : Assume disk 2 crashes

To recover the data of Disk2, we can apply X-OR operation on data block on disk 1 with corresponding parity block on Disk3.

 

Block 1 of Disk2 = block1 of disk1 (X-OR) parity block1 of disk3

                         = 1010 (X-OR) 1111

                        = 0101

 

Block 2 of Disk2 = block2 of disk1 (X-OR) parity block2 of disk3

                         = 1111 (X-OR) 0011

                        = 1100

 

Block 3 of Disk2 = block3 of disk1 (X-OR) parity block3 of disk3

                         = 0000 (X-OR) 1011

                        = 1011

 

Block 4 of Disk2 = block4 of disk1 (X-OR) parity block4 of disk3

                         = 0011 (X-OR) 1110

                        = 1101

 

 

RAID 5 (distributed parity)

RAID 5 uses something called distributed parity to protect against problems. Unlike RAID 4, where all the parity information is put on one drive, in RAID 5, this information is spread out among all the drives.




RAID6

In RAID 5, if one disk breaks, the data is still safe because it has a special block called parity. But RAID 6 is even safer because it can handle two disks failing at the same time, by having two parity blocks.

 

However, RAID 6 doesn't use space as efficiently as RAID 5 because it uses two parity blocks, which means some storage is used just for safety. This does make it more secure, though.

 

When it comes to how fast it can write data, RAID 6 is a bit slower than RAID 5 because it has to do more calculations with the extra parity. But when it comes to reading data, both RAID 5 and RAID 6 are usually about the same in terms of speed.

 

Is RAID replace backup plan?

No, using RAID doesn't mean you can skip having a backup plan. RAID helps keep your data safe if a disk breaks, but it can't protect against other issues like mistakes, software problems, or viruses. A good backup plan should cover all these possibilities, and RAID can be a part of that plan.

 

                                                             System Design Questions