Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to change a single value in pandas dataframe

I've seen a bunch of questions with similar titles but I still cant figure it out. All I want to do is replace the value thats in my dataframe in the fifth row and 5th column with the value 100. I thought simply this would do the trick

df.loc['cheerios','rating']= 100

since cheerios is the row and rating is the column

    name        sugar  sodium rating
0   fruit loop       x      x     x
1   trix             x      x     x
2   oreo             x      x     x
3  cocoa puff        x      x     x
4  cheerio           x      x     100
like image 516
Chelsea Lewis Avatar asked Jun 20 '18 00:06

Chelsea Lewis


People also ask

How do I change a specific value in pandas?

Pandas DataFrame replace() Method The replace() method replaces the specified value with another specified value. The replace() method searches the entire DataFrame and replaces every case of the specified value.

How do you replace a single value in a DataFrame?

(3) Replace multiple values with multiple new values for an individual DataFrame column: df['column name'] = df['column name']. replace(['1st old value','2nd old value',...],['1st new value','2nd new value',...])


1 Answers

.loc is an indexer. It looks for an entry in the index, but the column name is not an index. It is simply a column. The following solutions would work:

df.loc[4, 'rating'] = 100 # Because 4 is in the index, but how do you know?

or:

df.loc[df['name']=='cheerio', 'rating'] = 100 # Find the row by column

or:

df.set_index('name', inplace=True) # Make 'name' the index
df.loc['cheerios', 'rating'] = 100     # Use the indexer
like image 90
DYZ Avatar answered Nov 14 '22 21:11

DYZ