Sunday 21 January 2024

Pandas: apply some operation on every value of the column using apply method

Using apply method, we can invoke given function on each value of a Series. Following snippet convert the values in Name and City columns to upper case using apply method.

 

columns_to_update = ['Name', 'City']

for column in columns_to_update:

    df[column] = df[column].apply(to_upper)

 

'df[column].apply(to_upper)' statement invoke the function 'to_upper' on values of Series.

 

Find the below working application.

 

apply_transformation_on_column.py

import pandas as pd

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

def to_upper(input_str: str):
    return input_str.upper()

columns_to_update = ['Name', 'City']
for column in columns_to_update:
    df[column] = df[column].apply(to_upper)

print('\nDataFrame after converting the Name and City to uppercase')
print(df)

 

Output

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

DataFrame after converting the Name and City to uppercase
       Name  Age       City  Gender  Rating
0   KRISHNA   34  BANGALORE    Male      39
1     SAILU   35  HYDERABAD  Female      43
2      JOEL   29  HYDERABAD    Male      67
3     CHAMU   35    CHENNAI  Female     100
4  JITENDRA   52  BANGALORE    Male      41
5   KRISHNA   34    CHENNAI    Male      89

 

 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment