Monday, 4 December 2023

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

No comments:

Post a Comment