尝试在 Pandas 数据框中更改单个值

8
我看到了很多标题类似的问题,但仍然无法弄清楚。我想做的只是用值100替换数据框中第五行和第五列的值。 我认为这样简单的代码可以解决:
df.loc['cheerios','rating']= 100

由于Cheerios是行,评分是列

    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
2个回答

20

.loc是一个索引器。它在索引中查找条目,但列name不是索引,它只是一列。以下解决方案可行:

df.loc[4, 'rating'] = 100 # Because 4 is in the index, but how do you know?
或:
df.loc[df['name']=='cheerio', 'rating'] = 100 # Find the row by column
或者:
df.set_index('name', inplace=True) # Make 'name' the index
df.loc['cheerios', 'rating'] = 100     # Use the indexer

1
尝试使用 pandas.DataFrame.at
df.at[df['name'].tolist().index('cherrio'),'rating']=100
print(df)

输出:

    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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接