Predictive Hacks

Replace Values Based On Index In Pandas Dataframes

You can easily replace a value in pandas data frames by just specifying its column and its index.

import pandas as pd
import dataframe_image as dfi
 
df = pd.DataFrame({'A': [1,2,3,4],
                   'B':['A','B','C','D']})
 
Replace Values Based On Index In Pandas Dataframes

Having the dataframe above, we will replace some of its values. We are using the loc function of pandas. The first variable is the index of the value we want to replace and the second is its column.

df.loc[0,"A"]=20

df.loc[1,"B"]="Billy"
Replace Values Based On Index In Pandas Dataframes

The loc function also lets you set a range of indexes to be replaced as follows.

df.loc[0:2,"A"]=100

Replace Values Based On Index In Pandas Dataframes

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Join the inner circle

Join our 2.000+ members and receive exclusive
data science content 🧪