使用pandas更新数据框行的新值

12

我有一个文本文件,已经通过 df1 = pandas.read_csv(r'fruits.txt', sep=',') 被读入pandas。

    item  freshness
0   apple    2.2
1   pear     0.0

进行一系列计算以得出 apple = 2.3 的结果。

我能否使用pandas.update 来更新数据帧中 applefreshness 值为 2.3

1个回答

22

如果我理解正确,您需要 loc 函数:

apple = 2.3

print df['item'] == 'apple'
0     True
1    False
Name: item, dtype: bool

df.loc[df['item'] == 'apple', 'freshness'] = apple
print df
    item  freshness
0  apple        2.3
1   pear        0.0

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