newinPython
newinPython

Reputation: 313

Replace operation is not working in Pandas dataframe

I'm trying to replace the Marks field value for id 235 in my pandas data frame, df. Earlier it was 65 & I want to replace it to 75 So I wrote following code

df.at['235', 'Marks'] = 75

After that I'm trying to see if that replace is working or not.So I wrote

df.at['235', 'Marks']

and it's giving value as 75 But when I'm trying to see the columns against id by using following code

df[df['id']=='235'].head()

I'm seeing old value 65 in marks field. Can you please help me to correct it?

Upvotes: 0

Views: 271

Answers (2)

fibonachoceres
fibonachoceres

Reputation: 777

Is id the primary index of the dataframe? If you didn't do any additional modifications to the dataframe, using df.at['235', ...] would use the index first and not the column "id" that you reference later in the statement. The default index in pandas dataframes is the row number. df.loc[df['id'] == '235', 'Marks'] = should be the statement you're looking for.

An example that the pattern you're using should work if the correct index is supplied:-

data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
df.at[0, "Name"] = "lolname"
df.at[0, "Name"]
=> 'lolname'
df
=> 
      Name  Age
    0  lolname   10
    1      Bob   12
    2   Clarke   13

Upvotes: 1

Arun Palanisamy
Arun Palanisamy

Reputation: 5459

You can try using df.loc

df.loc[df.ID == 235, 'Marks'] = 75

df.at basically works based on row_num if it is not indexed.

Upvotes: 0

Related Questions