pandas 熊猫用新值更新数据框行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36531289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:01:33  来源:igfitidea点击:

pandas update dataframe row with new value

pythonpandas

提问by jake wong

I have a text file which has been read into pandas by df1 = pandas.read_csv(r'fruits.txt', sep=',')

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

    item  freshness
0   apple    2.2
1   pear     0.0

and a series of calculations that would yield the result of apple = 2.3

和一系列的计算,将产生的结果 apple = 2.3

Is it possible to do a pandas.updateso that I can update the value of freshnessfor applein the dataframe to 2.3?

是否可以执行 apandas.update以便我可以将数据框中的freshnessfor值更新apple2.3

回答by jezrael

IIUC you need loc:

IIUC你需要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