尝试更改熊猫数据框中的单个值

Che*_*wis 5 python python-3.x pandas

我已经看到一堆标题相似的问题,但我仍然无法弄清楚。我想要做的就是用值 100 替换我的数据框中第五行和第五列中的值。我认为这可以解决问题

df.loc['cheerios','rating']= 100
Run Code Online (Sandbox Code Playgroud)

因为cheerios 是行,而 rating 是列

    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
Run Code Online (Sandbox Code Playgroud)

DYZ*_*DYZ 9

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

df.loc[4, 'rating'] = 100 # Because 4 is in the index, but how do you know?
Run Code Online (Sandbox Code Playgroud)

或者:

df.loc[df['name']=='cheerio', 'rating'] = 100 # Find the row by column
Run Code Online (Sandbox Code Playgroud)

或者:

df.set_index('name', inplace=True) # Make 'name' the index
df.loc['cheerios', 'rating'] = 100     # Use the indexer
Run Code Online (Sandbox Code Playgroud)