close

how to replace values of selected row of a column in panda’s dataframe?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about how to replace values of selected row of a column in panda’s dataframe in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

how to replace values of selected row of a column in panda’s dataframe?

  1. how to replace values of selected row of a column in panda's dataframe?

    you can directly filter the rows you want to change and assign the value to it instead of filtering, replacing and then assigning to the dataframe.

  2. replace values of selected row of a column in panda's dataframe

    you can directly filter the rows you want to change and assign the value to it instead of filtering, replacing and then assigning to the dataframe.

Method 1

You can select by loc with condition rows of column Cabin and set to scalar:

train.loc[train['Pclass'] == 1, 'Cabin'] = 1

And your code replace all values to 1 because is is same as:

train['Cabin'] = 1

Sample:

train = pd.DataFrame({'Pclass':[1,2,3,1,2],
                      'Cabin':[10,20,30,40,50]})
print (train)
   Cabin  Pclass
0     10       1
1     20       2
2     30       3
3     40       1
4     50       2

train.loc[train['Pclass'] == 1, 'Cabin'] = 1
print (train)
   Cabin  Pclass
0      1       1
1     20       2
2     30       3
3      1       1
4     50       2

Method 2

you can directly filter the rows you want to change and assign the value to it instead of filtering, replacing and then assigning to the dataframe.

So

train[‘Cabin’] =train[train[‘Pclass’]==1][‘Cabin’]=1
becomes

train[‘Cabin’][train[‘Pclass’]==1] = 1

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read