.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
Answer from DYZ on Stack Overflowpython - Trying to change a single value in pandas dataframe - Stack Overflow
python - Replace single value in a pandas dataframe, when index is not known and values in column are unique - Stack Overflow
python - How do i replace the value of a data-frame column with a single value? - Stack Overflow
Pandas: Need to replace only a certain value with another value from a different dataframe.
.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
Try using pandas.DataFrame.at:
df.at[df['name'].tolist().index('cherrio'),'rating']=100
print(df)
Output:
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
I'm losing my mind on this one. I have two dataframes. For simplicity's sake, in df1, let's say there's a column with a project name, and a column with the project owner. Due to a change in systems, some project owners have been replaced with "Default." In df2, I have all the projects and project owners, but only for the "Default" folk. There are, of course, many other columns on both dataframes, but I'm omitting them. Also, the dataframes have completely different column names. I only mention because it's one of the errors I've run into. This is for a script I run every week for work that needs to be changed due to the aforementioned new system.
Example of df1:
| Project Name | Project Owner |
|---|---|
| Project A | Bob Jones |
| Project B | Default |
| Project C | Default |
| Project D | John Roberts |
Example of df2:
| Name of Project | Owner of Project |
|---|---|
| Project B | Bertha Thomas |
| Project C | Jane Smith |
I've tried:
project_dict = dict(zip(df2['Name of Project'], df2['Owner of Project'])) df['Project Owner'] = df['Project Name'].replace(project_dict)
Which outputs:
| Project Name | Project Owner |
|---|---|
| Project A | Project A |
| Project B | Bertha Thomas |
| Project C | Jane Smith |
| Project D | Project D |
I've also tried every way to use loc I could think of, and I'm just lost. The above is the closest I've gotten. Any ideas would be appreciated, and don't hesitate to let me know if I need to post more code.
Thanks!