Tuesday, 5 December 2023

Maintainability: The Cornerstone of Sustainable Software Development

Applications are expected to have a long life cycle. A maintainable design ensures that the application can be sustained over the long term, and provide a foundation for future enhancements. Apart from this, It's important to note that most of the money spent on software doesn't go into the initial development; rather, the majority is used for ongoing maintenance activities. This highlights the importance of designing software with a focus on long-term sustainability and cost-effective maintenance.

 

Now, let's talk about the regular maintenance activities that we do for a software application.

 

1. Bug Fixes: Resolving the issues reported by users or found during testing.

 

2. Environment Changes: Adjusting the software to accommodate alterations in the operating environment, like updates to hardware, software, or third-party dependencies upgrades etc.,

 

3. Enhancements: As time goes on, we might want to add new features or make the existing ones better to match what users need.

 

4. Code Refactoring: Sometimes to enhance maintainability of the application, we might need to refactor the existing code without changing its external behaviour.

 

5. Documentation Updates: We make sure that the guides and instructions about how to use the software are always correct and reflect any changes we've made.

 

6. UI/UX Enhancements: We improve how the software looks and how people interact with it to give a nicer experience.

 

7. Security Enhancements: We work on making sure bad guys can't harm the software. We fix any vulnerabilities to keep everything safe and secure.

 

8. Backing Up and Recovering Data: We regularly check that we can save and get back all the important information in case something unexpected happens, like losing data.

 

9. User Support and Training: We're always ready to help users if they have questions or problems. We might also teach them how to use the software better.

 

10. Getting Ready for the Future: We plan for the day when the software might need to retire (stop working) or be replaced with something newer. If we switch to a new version, we make sure it happens smoothly without causing trouble for users.

 

Principles to design a maintainable system

Creating a software system that is easy to maintain requires to adhere to several key principles that enhance code clarity, organization, and flexibility. These principles play a crucial role in ensuring the software's long-term understandability, adaptability, and scalability, ultimately lowering development costs and enhancing the overall success of the project.

 

1. Keep the things simple

Ensure that new engineers can grasp the system easily by minimizing complexity, which not only enhances understandability but also reduces the likelihood of introducing new bugs during modifications. Striving for simplicity is crucial for improving software maintainability.

 

Break down the software into small, independent modules. This approach facilitates a better understanding of, updates to, and maintenance of individual components without impacting the entire system.

 

Use Clear Naming Conventions, maintain consistency in naming variables, functions, and classes. This practice enhances code readability, making it more accessible for developers to collaborate on and maintain.

 

Embrace Abstractions, encourage for the use of effective abstractions, as they play a crucial role in reducing complexity and making the system more adaptable to new use cases.

 

2. Operable

Ensure that operations teams can effectively manage the system.

 

Operations teams are responsible for various maintenance activities, such as keeping software and platforms up-to-date, applying the security patches, monitoring the system's health, promptly restoring service in case of issues, planning for capacity, managing configurations, and migrating applications between platforms etc.,

 

When designing the system, it's essential to consider how operations can be streamlined. The application should facilitate automation, integrate seamlessly with standard tools, and have a comprehensive documentation that clearly outlines the system's behaviour on each configuration property change etc.,

 

3. Adaptable or Modifiable: Design the application in a way that facilitates easy modifications by engineers in the future, allowing for adjustments to unanticipated use cases as requirements evolve.

 

Following development principles/guidelines helps you to develope a simple, operable and adaptable software.

 

1. Open/Closed Principle (OCP): where Software entities should be open for extension but closed for modification.

 

2. Single Responsibility Principle (SRP): Each class or module should have a single well-defined responsibility. This principle promotes modularity and reduces coupling between components, making it easier to understand and maintain individual parts of the system.

 

3. Dependency Inversion Principle (DIP): Encourage a design where high-level modules don't tightly rely on low-level ones. Both should depend on abstractions. This principle promotes loose coupling and reduces dependencies between components, making it easier to test, debug, and maintain the system.

 

4. Liskov Substitution Principle: If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program. This principle ensures that inheritance relationships are well-defined and that subtypes behave consistently with their base types.

 

5. Eliminate duplication: Don't repeat yourself in your code. This makes everything more consistent and saves you from doing the same thing in multiple places.

 

6. Clean and comprehensive documentation: Write good and up-to-date guides for your code. It helps you and others understand how everything works.

 

7. High Cohesion and Loose coupling:  Keep related functionality within the same module or class and minimize dependencies between modules or components.

 

8. Testing: Incorporate thorough unit tests, integration tests, and system tests to ensure software correctness, reliability, and consistent behaviours in various conditions. It gives confidence to the developers to validate the new changes on a maintenance product.

                                                             System Design Questions

Monday, 4 December 2023

Quick overview on Scalability

 

Scalability is the term that we use to describe a system’s ability to cope with increased load. In simpler terms, it's about how well a system can handle more requests as demand increase.

 

For instance, you could have constructed a system with the expectation that it would handle a maximum of 1 million users. However, as time passes, your application gains popularity, and the user base unexpectedly surges from 1 million to 10 million. If you haven't taken scalability into account when designing the system, its performance could decline or even crash when faced with an unforeseen increase in demand.

 

There are two main types of scalability:

 

Vertical Scaling

Involves increasing the capacity of a single machine or resource within a system. For example, adding more memory, upgrading the CPU, or expanding storage on a single server.

 

Horizontal Scaling

Involves adding more machines or nodes to a network or system.

For example, instead of upgrading a single server, you add more servers to distribute the workload.

 

Following are some questions that can guide you in assessing and planning for scalability

 

1. User load

How many users do we expect to use the system concurrently?

What is the anticipated growth rate in user numbers over time?

What happen to the application, when the load doubles, triples etc.,?

What different types of users will access the system and what are their usage patterns?

 

2. Transaction or requests Rate

How many transactions or operations does the system need to handle per unit of time?

Are there specific operations that are more resource-intensive?

Can the system handle sudden spikes in traffic or data influx?

 

3. Resource Utilization

How efficiently are the system's resources (CPU, memory, storage) utilized under current load?

Is there room for optimization in resource usage?

 

4. Response Time Expectations

What are the acceptable response time thresholds for different types of requests?

How quickly should the system respond under varying loads?

What are the acceptable latency levels under different load conditions?

 

5. Load Balancing

How is the workload distributed across multiple servers or nodes?

Is there an effective load balancing strategy in place?

 

6. Disaster recovery and Failure Handling

How does the system handle failures or unexpected events under heavy load?

Is there a strategy for graceful degradation in case of overload?

How will the system handle failures or outages at different scales?

What mechanisms are in place for replication, backups, and disaster recovery?

Can the system automatically recover from failures without significant downtime?

How will scalability impact disaster recovery plans and procedures?

 

7. Caching Strategies

What data can be cached to reduce the need for repeated processing?

Are there opportunities to implement effective caching mechanisms?

 

8. Database Scaling

How does the database handle increased data volume and transaction rates?

Is there a strategy for database scaling, such as sharding or replication?

 

9. Data Handling

How much data does the system need to manage, and how is it distributed?

What is the anticipated growth rate in data volume?

 

10. Traffic Patterns

What are the peak hours or periods of high user activity?

Are there specific events or conditions that may cause a sudden increase in traffic?

 

11. Infrastructure Architecture

Is the system designed for vertical scaling, horizontal scaling, or a combination of both?

What cloud or server infrastructure is being used, and how easily can it scale?

How can we add computing resources to handle the additional load?

What are the possible options I have to cope with the traffic growth?

What are the limitations of current Architecture?

Are there any dependencies on external systems that impact scalability?

 

12. Code Optimization

Are there areas in the codebase that can be optimized for better performance?

How well does the code handle concurrent requests?

 

By addressing these questions in depth, you can build a thorough understanding of your scalability requirements and make well-informed decisions on how to achieve them successfully. Keep in mind that scalability is an ongoing process, so consistently monitoring, assessing, and adjusting your approach is crucial for long-term success.

 

How to describe a load on the system?

Describing the load varies from application to application. In case of microservices, we can describe the load by number of requests per second, in case of data processing engine, we can describe the load by  ‘How much time it takes to run a Job of specific dataset size?’

 

Following are the key aspects to consider when describing the load on a system.

 

1. Number of Requests

Number of requests per second

Number of reads and writes to a database

 

2. Concurrency

Number of requests being processed simultaneously.

Number of users supported simultaeously

Number of active sessions

 

3. Type of load

User-initiated: Arising from users engaging directly with the system, such as logins, transactions, or API calls.

Data-driven: Arising from the processing or transfer of data, including batch jobs, ETL pipelines, or file uploads.

 

4. Resource utilization

CPU, memory, disk, network bandwidth usage.

 

5. Error rate

Frequency of errors or failures under load.

 

By focusing on  these elements clearly, you can create a clear understanding of the load and its consequences, facilitating well-informed decisions regarding system optimization, capacity planning, and managing diverse demands. Keep in mind that the emphasis on specific details should align with your context and audience.

 

                                                             System Design Questions

Pandas: Set values to specific columns using iloc accessor

In this post, I am going to explain how to set values to specific columns using iloc accessor.

 

Example 1: Setting the value of a specific row and column

df.iloc[row_index, column_index_to_update] = 'new_value'

 

Example 2: Setting the value of a specific row and multiple columns

df.iloc[row_index, columns_to_update] = [new_value_1, new_value_2]

 

Find the below working application.

 

set_values_to_multiple_columns.py

import pandas as pd

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

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

print('\nSet "Name" column as index column')
df.set_index('Name', inplace=True)
print(df)

# Setting the value of a specific row and column
row_index = 0
column_index_to_update = 1
df.iloc[row_index, column_index_to_update] = 'Chennai'
print('\nSetting te City of Krishna to "Chennai"')
print(df)

# Setting the value of a specific row and multiple columns
row_index = 0
columns_to_update = [0, 3]
df.iloc[row_index, columns_to_update] = [45, 35]
print('\nUpdating the Age and Rating of Krishna')
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

Set "Name" column as index column
         Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100

Setting te City of Krishna to "Chennai"
         Age       City  Gender  Rating
Name                                   
Krishna   34    Chennai    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100

Updating the Age and Rating of Krishna
         Age       City  Gender  Rating
Name                                   
Krishna   45    Chennai    Male      35
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100

 


Previous                                                 Next                                                 Home

Pandas: Set values to a specific columns using loc access specifier

In this post, I am going to explain how to set values to a specific columns using loc access specifier.

 

Example 1: Setting the value of a specific row and column

df.loc[row_label, column_to_update] = 'new_value'

 

Example 2: Updating multiple columns

df.loc[row_label, columns_to_update] = [new_val1, new_val2]

 

set_values_to_multiple_columns.py

import pandas as pd

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

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

print('\nSet "Name" column as index column')
df.set_index('Name', inplace=True)
print(df)

# Setting the value of a specific row and column
row_label = 'Krishna'
column_to_update = 'City'
df.loc[row_label, column_to_update] = 'Chennai'
print('\nSetting the City of Krishna to "Chennai"')
print(df)

# Setting the value of a specific row and multiple columns
row_label = 'Krishna'
columns_to_update = ['Age', 'Rating']
df.loc[row_label, columns_to_update] = [45, 35]
print('\nUpdating the Age and Rating of Krishna')
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

Set "Name" column as index column
         Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100

Setting the City of Krishna to "Chennai"
         Age       City  Gender  Rating
Name                                   
Krishna   34    Chennai    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100

Updating the Age and Rating of Krishna
         Age       City  Gender  Rating
Name                                   
Krishna   45    Chennai    Male      35
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100

 

 

Previous                                                 Next                                                 Home

Pandas: loc: Access the DataFrame rows using row labels

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

Using ‘loc’ accessor, we can access and manipulate data in a DataFrame using label-based indexing.

 

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  Krishna   52  Bangalore    Male      87
5      Raj   34    Chennai    Male      89

Example 1: Access a single row by its label

df.loc[row_label_1]

 

Example 2: Access multiple rows by their labels

df.loc[[row_label_1, row_label_2]]

 

Example 3: Access specific column of the row

df.loc[row_label_1, column_label_1]

 

Example 4: Access specific column2 of the row

df.loc[row_label_1, [column_label_1, column_label_2]]

 

Example 5: Access multiple rows and columns

df.loc[[row_label_1, row_label_2], [column_label_1, column_label_2]]

 

Example 6: Access all rows for specific columns

df.loc[:, [column_label_1, column_label_2]]

 

Find the below working application.

 

loc_hello_world.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Krishna', "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)

print('\nSet "Name" column as index column')
df.set_index('Name', inplace=True)
print(df)

row_label_1 = 'Krishna'
row_label_2 = 'Chamu'

column_label_1 = 'City'
column_label_2 = 'Age'

# Access a single row by its label
result = df.loc[row_label_1]
print('\nAccess a single row by its label :\n',result)

# Access multiple rows by their labels
result = df.loc[[row_label_1, row_label_2]]
print('\nAccess multiple rows by their labels :\n',result)

# Access specific column of the row
result = df.loc[row_label_1, column_label_1]
print('\nAccess specific column of the row :\n',result)

# Access specific columns of the row
result = df.loc[row_label_1, [column_label_1, column_label_2]]
print('\nAccess specific columns of the row :\n',result)

# Access multiple rows and columns
result = df.loc[[row_label_1, row_label_2], [column_label_1, column_label_2]]
print('\nAccess multiple rows and columns :\n',result)

# Access all rows for specific columns
result = df.loc[:, [column_label_1, column_label_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  Krishna   52  Bangalore    Male      87
5      Raj   34    Chennai    Male      89

Set "Name" column as index column
         Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100
Krishna   52  Bangalore    Male      87
Raj       34    Chennai    Male      89

Access a single row by its label :
          Age       City Gender  Rating
Name                                  
Krishna   34  Bangalore   Male      81
Krishna   52  Bangalore   Male      87

Access multiple rows by their labels :
          Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Krishna   52  Bangalore    Male      87
Chamu     35    Chennai  Female     100

Access specific column of the row :
 Name
Krishna    Bangalore
Krishna    Bangalore
Name: City, dtype: object

Access specific columns of the row :
               City  Age
Name                   
Krishna  Bangalore   34
Krishna  Bangalore   52

Access multiple rows and columns :
               City  Age
Name                   
Krishna  Bangalore   34
Krishna  Bangalore   52
Chamu      Chennai   35

Access all rows for specific columns :
               City  Age
Name                   
Krishna  Bangalore   34
Sailu    Hyderabad   35
Joel     Hyderabad   29
Chamu      Chennai   35
Krishna  Bangalore   52
Raj        Chennai   34

Following are the common uses of loc accessor

a.   Access rows and columns

b.   Slicing with index labels

c.    Boolean indexing

d.   Assigning values

 

Access rows and columns

This is already covered in the introduction part of this post.

 

Slicing with index labels

Example 1: Slicing rows based on index labels. Here both 'row_label_1' and 'row_label_2' are inclusive.

 

df.loc['row_label_1':'row_label_2']

 

Example 2: Slicing rows and selecting specific columns. Here 'row_label_1', 'row_label_2', 'column_label_1' and 'column_label_2' are inclusive.

 

df.loc['row_label_1':'row_label_2', 'column_label_1':'column_label_2']

 

slicing.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Ram', "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)

print('\nSet "Name" column as index column')
df.set_index('Name', inplace=True)
print(df)

row_label_1 = 'Krishna'
row_label_2 = 'Chamu'

column_label_1 = 'Age'
column_label_2 = 'Gender'

# Slicing rows based on index labels
result = df.loc[row_label_1:row_label_2]
print('\nSlicing rows based on index labels:\n',result)

# Slicing rows and selecting specific columns
result = df.loc[row_label_1:row_label_2, column_label_1:column_label_2]
print('\nSlicing rows and selecting 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      Ram   52  Bangalore    Male      87
5      Raj   34    Chennai    Male      89

Set "Name" column as index column
         Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100
Ram       52  Bangalore    Male      87
Raj       34    Chennai    Male      89

Slicing rows based on index labels:
          Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100

Slicing rows and selecting specific columns
          Age       City  Gender
Name                           
Krishna   34  Bangalore    Male
Sailu     35  Hyderabad  Female
Joel      29  Hyderabad    Male
Chamu     35    Chennai  Female

Boolean indexing

Example 1: Access rows based on a condition

age_greater_34 = df.loc[df['Age'] > 34]

 

Example 2: Access rows based on multiple conditions

age_greater_34_city_hyderabad = df.loc[(df['Age'] > 34) & (df['City'] == 'Hyderabad')]

 

boolean_indexing.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Ram', "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)

print('\nSet "Name" column as index column')
df.set_index('Name', inplace=True)
print(df)

# Access rows based on a condition
age_greater_34 = df.loc[df['Age'] > 34]
print('\nage_greater_34\n',age_greater_34)

# Access rows based on multiple conditions
age_greater_34_city_hyderabad = df.loc[(df['Age'] > 34) & (df['City'] == 'Hyderabad')]
print('\nage_greater_34_city_hyderabad:\n',age_greater_34_city_hyderabad)

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      Ram   52  Bangalore    Male      87
5      Raj   34    Chennai    Male      89

Set "Name" column as index column
         Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100
Ram       52  Bangalore    Male      87
Raj       34    Chennai    Male      89

age_greater_34
        Age       City  Gender  Rating
Name                                 
Sailu   35  Hyderabad  Female      76
Chamu   35    Chennai  Female     100
Ram     52  Bangalore    Male      87

age_greater_35_city_hyderabad:
        Age       City  Gender  Rating
Name                                 
Sailu   35  Hyderabad  Female      76

Assigning values

Example 1: Assign a value to a specific cell

df.loc[row_label, column_label] = new_value

 

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

df.loc[df['City'] == 'Hyderabad', 'City'] = 'Mumbai'

 

assign_values.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Ram', "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)

print('\nSet "Name" column as index column')
df.set_index('Name', inplace=True)
print(df)

row_label = 'Joel'
column_label = 'City'
new_value = 'Delhi'
# Assign a value to a specific cell
df.loc[row_label, column_label] = new_value
print('\nSetting Joel\' City to Delhi.\n', df)

# Assign a value to multiple cells based on a condition
df.loc[df['City'] == 'Hyderabad', 'City'] = 'Mumbai'
print('\nSetting the city to Mumbai where the City is Hyderabad.\n',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      Ram   52  Bangalore    Male      87
5      Raj   34    Chennai    Male      89

Set "Name" column as index column
         Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100
Ram       52  Bangalore    Male      87
Raj       34    Chennai    Male      89

Setting Joel' City to Delhi.
          Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29      Delhi    Male      67
Chamu     35    Chennai  Female     100
Ram       52  Bangalore    Male      87
Raj       34    Chennai    Male      89

Setting the city to Mumbai where the City is Hyderabad.
          Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Sailu     35     Mumbai  Female      76
Joel      29      Delhi    Male      67
Chamu     35    Chennai  Female     100
Ram       52  Bangalore    Male      87
Raj       34    Chennai    Male      89

 

 

Previous                                                 Next                                                 Home