Monday 4 December 2023

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

No comments:

Post a Comment