Monday, 29 January 2024

Pandas: replace string values in a DataFrame

Using 'replace()' method, we can perform string replacement operations in a dataframe

 

Example 1: Replace the values in a specific column.

df['City'] = df['City'].str.replace('Bangalore', 'Mumbai')

 

In the above example, the value 'Bangalore' in the 'City' column is replaced with 'Mumbai'. This is done by selecting the 'City' column using df['City'] and using the replace() method with the specified values to be replaced.

 

Example 2: Replace the values across dataframe by specifying a dictionary.

 

replace_dict = {'Krishna': 'Hari', 'Hyderabad': 'Delhi'}
df = df.replace(replace_dict)

 

replace_dict specifies the mapping values 'Krishna' to 'Hari' and 'Hyderabad' to 'Delhi'. The replace() method is then used on the entire DataFrame, replacing the values based on the dictionary mapping.

 

Find the below working application.

 

replace.py

 

import pandas as pd

# Create a sample DataFrame
data = {'Title': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Krishna"],
        'Age': [34, 35, 234, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [67, 43, 67, 100, 41, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

df['City'] = df['City'].str.replace('Bangalore', 'Mumbai')
print('\nDataFrame after replacing City value Hyderabad to Mumbai\n', df)

# Replace values in multiple columns
replace_dict = {'Krishna': 'Hari', 'Hyderabad': 'Delhi'}
df = df.replace(replace_dict)
print('\nDataframe after replacing the dictionary of values\n', df)

Output

Original DataFrame
      Title  Age       City  Gender  Rating
0   Krishna   34  Bangalore    Male      67
1     Sailu   35  Hyderabad  Female      43
2      Joel  234  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52  Bangalore    Male      41
5   Krishna   34    Chennai    Male      89

DataFrame after replacing City value Hyderabad to Mumbai
       Title  Age       City  Gender  Rating
0   Krishna   34     Mumbai    Male      67
1     Sailu   35  Hyderabad  Female      43
2      Joel  234  Hyderabad    Male      67
3     Chamu   35    Chennai  Female     100
4  Jitendra   52     Mumbai    Male      41
5   Krishna   34    Chennai    Male      89

Dataframe after replacing the dictionary of values
       Title  Age     City  Gender  Rating
0      Hari   34   Mumbai    Male      67
1     Sailu   35    Delhi  Female      43
2      Joel  234    Delhi    Male      67
3     Chamu   35  Chennai  Female     100
4  Jitendra   52   Mumbai    Male      41
5      Hari   34  Chennai    Male      89




 

Previous                                                 Next                                                 Home

Pandas: Get length of each string in a given column

'len()' method return the length of each string in a given column.

Example

df['No_of_chars_in_city'] = df['City'].str.len()

As you see above snippet, we are using 'str' accessor to perform the string operations. 'df['City'].str.len()' calculates the length of each string in the 'City' column and creates a new column 'No_of_chars_in_city' with the respective lengths.

 

Find the below working application.

 

len.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['krishna gurram', 'sailu nava', 'joel chelli', 'chamu mag', 'Jitendra khod', "Krishna battu"],
        'Age': [34, 35, 234, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [67, 43, 67, 100, 41, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

df['No_of_chars_in_city'] = df['City'].str.len()

print('\nDataFrame after adding new column NoOfCharsInCity\n', df)

Output

Original DataFrame
             Name  Age       City  Gender  Rating
0  krishna gurram   34  Bangalore    Male      67
1      sailu nava   35  Hyderabad  Female      43
2     joel chelli  234  Hyderabad    Male      67
3       chamu mag   35    Chennai  Female     100
4   Jitendra khod   52  Bangalore    Male      41
5   Krishna battu   34    Chennai    Male      89

DataFrame after adding new column NoOfCharsInCity
              Name  Age       City  Gender  Rating  No_of_chars_in_city
0  krishna gurram   34  Bangalore    Male      67                    9
1      sailu nava   35  Hyderabad  Female      43                    9
2     joel chelli  234  Hyderabad    Male      67                    9
3       chamu mag   35    Chennai  Female     100                    7
4   Jitendra khod   52  Bangalore    Male      41                    9
5   Krishna battu   34    Chennai    Male      89                    7

 

Previous                                                 Next                                                 Home

Pandas: Convert all the column values to title case

'title()' method converts the Strings in given column to title case and return a new series with the updated data.

Example

df['Name'] = df['Name'].str.title()

As you see above snippet, we are using 'str' accessor to perform the string operations

 

Find the below working application.

 

title_case.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['krishna gurram', 'sailu nava', 'joel chelli', 'chamu mag', 'Jitendra khod', "Krishna battu"],
        'Age': [34, 35, 234, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Rating': [67, 43, 67, 100, 41, 89]}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

df['Name'] = df['Name'].str.title()

print('\nDataFrame after converting the names to title case \n', df)

Output

Original DataFrame
             Name  Age       City  Gender  Rating
0  krishna gurram   34  Bangalore    Male      67
1      sailu nava   35  Hyderabad  Female      43
2     joel chelli  234  Hyderabad    Male      67
3       chamu mag   35    Chennai  Female     100
4   Jitendra khod   52  Bangalore    Male      41
5   Krishna battu   34    Chennai    Male      89

DataFrame after converting the names to title case 
              Name  Age       City  Gender  Rating
0  Krishna Gurram   34  Bangalore    Male      67
1      Sailu Nava   35  Hyderabad  Female      43
2     Joel Chelli  234  Hyderabad    Male      67
3       Chamu Mag   35    Chennai  Female     100
4   Jitendra Khod   52  Bangalore    Male      41
5   Krishna Battu   34    Chennai    Male      89

 

Previous                                                 Next                                                 Home

How the Eisenhower Matrix Boosts Your Software Dev Game?

The Eisenhower Matrix, sometimes called the Urgent-Important Matrix or Eisenhower Box, is a well-known method for organizing your tasks. It's named after Dwight D. Eisenhower, a former US President, who was really good at managing his time.

This method sorts tasks into four categories, making it easier for you and your team to figure out what to do first. It's like a guide for where to put your effort and time. The four categories are depicted in below image.

 


1. Urgent and Important (Quadrant I): These are the tasks you need to do right away because they're very important. For example, fixing major bugs that could cause problems for your product, rushing to get things ready for a demo, or dealing with security issues.

 

2. Important but Not Urgent (Quadrant II): These tasks are important for your success in the long run, but you don't need to do them right now. This includes making your code better and easier to work with, writing tests to check your code, documenting your work so others understand it, and going to conferences to learn more. Spending time on these helps you have fewer urgent tasks later on.

 

3. Urgent but Not Important (Quadrant III): These tasks need to be done soon, but they're not really important for your big goals. They're often about handling less important customer support issues, going to meetings that don't relate to what you're working on, and replying to emails that aren't very important. If you can, let someone else do these tasks.

 

4. Neither Urgent nor Important (Quadrant IV): These are things that you don't need to do right away, and they're not important. They're usually distractions like watching too much TV, sitting in meetings that don't help you, constantly checking social media, or working on small projects that don't fit with your main goals.

 

The Eisenhower Matrix helps you figure out which tasks are most important and should be done first. The goal is to spend more time on tasks that are important but not urgent, as these are the ones that really help you achieve your long-term goals. This way, you're not always just reacting to emergencies or doing things that others want but aren't really important for you.

 

Example 1: Deciding what to do first in a project:

Urgent & Important: These are the tasks you need to handle immediately because they're really important. For example, fixing critical problems in your software that could cause it to stop working correctly, rushing to get ready for a presentation or a product launch, or dealing with security vulnerabilities etc.,

 

Important & Not Urgent: These tasks are important for making your work better in the long run, but they don't have to be done right away. This includes refactoring your code so it's easier to understand and manage later, Improvise tests to check if your code works properly, making detailed documentation about how your software works (like for APIs), and going to conferences where you can learn new things related to your work.

 

Urgent & Not Important: These tasks need to be done soon, but they're not key to your main goals. They often involve things like dealing with customer problems that aren't very serious, going to meetings that don't have much to do with what you're currently working on, or replying to emails that aren't very urgent.

 

Not Important & Not Urgent: These are things that you don't need to do right now, and they don't really help you achieve your main goals. They are usually distractions like sitting in meetings that don't add any value, checking social media a lot, or working on small projects that aren't related to your main work.

 

By using this method, you can figure out which tasks are the most critical and need your attention first, which ones you should plan to do later, and which ones you can either give to someone else or not do at all. This way, you can focus on what really matters and manage your time better.


                                                             System Design Questions

Convert a list to tuple in Python

Tuples in Python are similar to lists in that they are ordered collections of items, but they differ in being immutable, meaning once created, their contents cannot be changed.

Following are the various approaches to convert a list to a tuple.

 

Approach 1: Using tuple() function.

 

Example

primes_list = [2, 3, 5, 7, 11]
primes_tuple = tuple(primes_list)

In the above Python snippet, a list of prime numbers is first created and then converted into a tuple. Initially, primes_list is defined as a list containing the first five prime numbers: 2, 3, 5, 7, and 11. Lists in Python are mutable, ordered collections of items, which in this case are integer values representing prime numbers. Following this, primes_tuple is created by converting primes_list into a tuple using the tuple() function.

>>> primes_list = [2, 3, 5, 7, 11]
>>> primes_tuple = tuple(primes_list)
>>> 
>>> primes_list
[2, 3, 5, 7, 11]
>>> type(primes_list)
<class 'list'>
>>> 
>>> 
>>> primes_tuple
(2, 3, 5, 7, 11)
>>> type(primes_tuple)
<class 'tuple'>

Approach 2: Using unpacking (*) operator.

 

Example

primes_list = [2, 3, 5, 7, 11]
primes_tuple = (*primes_list,)

In the above Python code, a list of prime numbers is initially defined, and then this list is converted into a tuple using the unpacking operator *.

>>> primes_list = [2, 3, 5, 7, 11]
>>> primes_tuple = (*primes_list,)
>>> 
>>> primes_list
[2, 3, 5, 7, 11]
>>> type(primes_list)
<class 'list'>
>>> 
>>> 
>>> primes_tuple
(2, 3, 5, 7, 11)
>>> type(primes_tuple)
<class 'tuple'>

Approach 3: Using for loop.

 

Example

primes_list = [2, 3, 5, 7, 11]
primes_tuple = ()

for item in primes_list:
   primes_tuple += (item,)

Above snippet demonstrates a process for converting a list of prime numbers into a tuple through iteration. The code begins by defining primes_list, a list containing the first five prime numbers: 2, 3, 5, 7, and 11. The conversion from the list to the tuple is achieved using a for loop. The loop iterates over each item in primes_list. Within the loop, the current item is added to primes_tuple using the += operator, which in the context of a tuple, creates a new tuple by concatenating the existing primes_tuple with a new tuple containing the current item, (item,).

>>> primes_list = [2, 3, 5, 7, 11]
>>> primes_tuple = ()
>>> 
>>> for item in primes_list:
...    primes_tuple += (item,)
... 
>>> 
>>> primes_list
[2, 3, 5, 7, 11]
>>> type(primes_list)
<class 'list'>
>>> 
>>> 
>>> primes_tuple
(2, 3, 5, 7, 11)
>>> type(primes_tuple)
<class 'tuple'>


 

Previous                                                 Next                                                 Home

Sunday, 28 January 2024

Convert tuple to a list in Python

Approach 1: Using list() function

Using list() function, we can convert a tuple to list.

 

Example

emp = (1, 'Krishna', 'Bangalore', 34)
emp_as_list = list(emp)

 

emp_as_list = list(emp)

This line converts the emp tuple into a list. The list() function is a built-in Python function that takes an iterable (like a tuple, a set, or a dictionary) and returns a new list with the same elements. In this case, emp_as_list becomes a list containing the same elements as the emp tuple: [1, 'Krishna', 'Bangalore', 34].

>>> emp = (1, 'Krishna', 'Bangalore', 34)
>>> emp_as_list = list(emp)
>>> 
>>> emp
(1, 'Krishna', 'Bangalore', 34)
>>> type(emp)
<class 'tuple'>
>>> 
>>> 
>>> emp_as_list
[1, 'Krishna', 'Bangalore', 34]
>>> type(emp_as_list)
<class 'list'>

Approach 2: Using list comprehensions.

emp = (1, 'Krishna', 'Bangalore', 34)
emp_as_list = [item for item in emp]

emp_as_list = [item for item in emp]

This line uses a list comprehension to convert the emp tuple into a list. List comprehensions are a concise way to create lists in Python. The syntax [item for item in emp] means "create a list consisting of each item taken from the emp tuple." This process iterates over each element in the emp tuple and places each element into a new list. The result is that emp_as_list becomes a list containing the same elements as the emp tuple: [1, 'Krishna', 'Bangalore', 34].

>>> emp = (1, 'Krishna', 'Bangalore', 34)
>>> emp_as_list = [item for item in emp]
>>> 
>>> emp
(1, 'Krishna', 'Bangalore', 34)
>>> type(emp)
<class 'tuple'>
>>> 
>>> 
>>> emp_as_list
[1, 'Krishna', 'Bangalore', 34]
>>> type(emp_as_list)
<class 'list'>

Approach 3: using for loop

emp = (1, 'Krishna', 'Bangalore', 34)
emp_as_list = []
for item in emp:
  emp_as_list.append(item)

 

emp_as_list = []

This line initializes an empty list named emp_as_list. In Python, lists are mutable and ordered collections of items. This list is intended to store the elements of the emp tuple.

 

for item in emp:

Above snippet iterates over each element in the emp tuple.

 

emp_as_list.append(item):

Inside the for loop, each item from the tuple emp is appended to the list emp_as_list using the append() method. This method adds the item to the end of the list.

>>> emp = (1, 'Krishna', 'Bangalore', 34)
>>> emp_as_list = []
>>> for item in emp:
...   emp_as_list.append(item)
... 
>>> 
>>> emp
(1, 'Krishna', 'Bangalore', 34)
>>> type(emp)
<class 'tuple'>
>>> 
>>> emp_as_list
[1, 'Krishna', 'Bangalore', 34]
>>> type(emp_as_list)
<class 'list'>

 

Approach 4: Using unpacking (*) operator

emp = (1, 'Krishna', 'Bangalore', 34)
emp_as_list = [*emp]

emp_as_list = [*emp]

This line converts the emp tuple into a list. The * operator, known as the unpacking operator in Python, is used here to unpack the elements of the tuple emp. When used within the square brackets [], it effectively takes all elements from the tuple and places them into a new list.

>>> emp = (1, 'Krishna', 'Bangalore', 34)
>>> emp_as_list = [*emp]
>>> 
>>> emp
(1, 'Krishna', 'Bangalore', 34)
>>> type(emp)
<class 'tuple'>
>>> 
>>> emp_as_list
[1, 'Krishna', 'Bangalore', 34]
>>> type(emp_as_list)
<class 'list'>

Sometimes, you might want to apply some transformations on the tuple elements while adding them to a list, you can combine list with map function to achieve this.

 

hobbies_as_list = list(map(lambda x : x.upper(), hobbies))

Above statement convert each hooby in the tuple to uppercase while adding to the list.

 

lambda x : x.upper(): This is a lambda function, an anonymous (nameless) function in Python. x is the input parameter, and x.upper() is the operation performed on this parameter. x.upper() converts the string x to uppercase.

 

map(lambda x : x.upper(), hobbies): The map function applies the lambda function to each element of the hobbies tuple. The map function takes two arguments: a function and an iterable (in this case, the hobbies tuple). It applies the given function (the lambda function) to each item of the iterable and returns a map object.

 

list(...): The map object returned by the map function is then converted into a list using the list() constructor. This is necessary because map returns a map object, not a list, and the goal here is to have a list of the modified elements.

>>> hobbies = ('football', 'cricket', 'singing', 'cooking')
>>> hobbies_as_list = list(map(lambda x : x.upper(), hobbies))
>>> 
>>> hobbies
('football', 'cricket', 'singing', 'cooking')
>>> type(hobbies)
<class 'tuple'>
>>> 
>>> 
>>> hobbies_as_list
['FOOTBALL', 'CRICKET', 'SINGING', 'COOKING']
>>> type(hobbies_as_list)
<class 'list'>

 

Previous                                                 Next                                                 Home