Sunday 21 January 2024

Pandas: Generate new column by applying a method on row values

 

In this post, I am going to explain how to generate new column data by applying a method on existing row values.

 

Let's use the below dataset to demonstrate the example.

 

       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

 

I want to add 'AboutMe' column to the existing dataset.

 

def about_me(row):

    name = row[0]

    age = row[1]

    city = row[2]

 

    about_me = f'I am {name} from {city} and I am {age} years old'

    return about_me

 

df['AboutMe'] = df.apply(about_me, axis='columns')

axis='columns' applies the mehtod about_me to all the columns of each row.

 

Find the below working application.

 

generate_new_columns_using_apply.py

import pandas as pd

pd.set_option('display.max_columns', None)
pd.set_option('display.width', 2000)

# 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 about_me(row):
    name = row[0]
    age = row[1]
    city = row[2]

    about_me = f'I am {name} from {city} and I am {age} years old'
    return about_me

# Add new column AboutMe to the existing data set
df['AboutMe'] = df.apply(about_me, axis='columns')
print('\n',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

        Name  Age       City  Gender  Rating                                            AboutMe
0   Krishna   34  Bangalore    Male      39  I am Krishna from Bangalore and I am 34 years old
1     Sailu   35  Hyderabad  Female      43    I am Sailu from Hyderabad and I am 35 years old
2      Joel   29  Hyderabad    Male      67     I am Joel from Hyderabad and I am 29 years old
3     Chamu   35    Chennai  Female     100      I am Chamu from Chennai and I am 35 years old
4  Jitendra   52  Bangalore    Male      41  I am Jitendra from Bangalore and I am 52 years...
5   Krishna   34    Chennai    Male      89    I am Krishna from Chennai and I am 34 years old

 


Previous                                                 Next                                                 Home

No comments:

Post a Comment