更改数据框中的特定值

时间:2020-05-30 14:46:29

标签: python pandas

我有这样的df:

from tornado import gen
from tornado.ioloop import IOLoop

async def f():
while True:
    await gen.sleep(0.100)
    record = create_record()
    source.emit(record, asynchronous = True)

IOLoop.current().add_callback(f)

我想根据它们的NUM_SC将一些值乘以(-1)。例如,对于NUM_SC中的511和127,将值乘以(-1)。对我有用的是:

Name   Value       NUM_SC

A      1000        421

B      2000        127

C      3000        511

D      2000        718

E      1500        511 (may duplicate)

其中 negative_sc 包含NUM_SC,我希望将其乘以(-1)。在此示例中,negative_sc =(511,127)。

但是这种方法需要很多时间。我尝试过这样的事情:

for i in negative_sc:
    for j in range(76818):
        if df.NUM_SC[j] == i:
            df.Values[j] *= (-1)

但是这产生了错误并且没有产生任何结果。

处理此类任务的最佳方法是什么?根据另一列中的值更改一列中的值

非常感谢!

2 个答案:

答案 0 :(得分:1)

您不应链接[ ].column_name。因此df.Values[j] *= -1df[df.NUM_SC == i].Values *= -1都不起作用。有关详细信息,请参见this document

代替:

df.loc[df.NUM_SC.isin(negative_sc), 'Values'] *= -1

答案 1 :(得分:0)

尝试使用isin为您要否定的列创建掩码。

import queue

# Initializing a queue
qW = queue.Queue(maxsize=20)

# qsize() give the maxsize of the Queue
print(qW.qsize())