pandas 如何更新数据帧值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36344106/
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 00:58:17  来源:igfitidea点击:

How to update dataframe value

pythonpython-2.7pandas

提问by Mateyobi

I have a project where for each row in a table I need to iterate through rows from another table and update values in both. The changes need to stick for the next iteration. What is the best way to do that?

我有一个项目,对于表中的每一行,我需要遍历另一个表中的行并更新两个表中的值。这些更改需要在下一次迭代中保持不变。最好的方法是什么?

for invoice_line in invoices.itertuples():
    qty = invoice_line.SHIP_QTY
    for receipt_line in receipts[receipts.SKU == invoice_line.SKU].itertuples():
        if qty > receipt_line.REC_QTY:
            receipts.set_value(receipt_line.index,'REC_QTY',0)
            qty = qty - receipt_line.REC_QTY
        else:
            receipts.set_value(receipt_line.index,'REC_QTY', receipt_line.REC_QTY - qty)
            qty = 0
        recd = receipt_line.REC_DATE
        if qty < 1:break
    invoices.set_value(invoice_line.index,'REC_DATE',recd)

set_value does not seem to work.

set_value 似乎不起作用。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD'))

for row in df.itertuples():
    df.set_value(row.index,'test',row.D)

print df.head()

回答by John

I think what you want is a capitalized Index

我认为你想要的是大写 Index

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD'))

for row in df.itertuples():
    df.set_value(row.Index,'test',row.D)

print df.head()

回答by Sam

Not 100% sure if this is what you want, but I think you're trying to loop thru a list and update the value of a cell in a dataframe. The syntax for that is:

不是 100% 确定这是否是您想要的,但我认为您正在尝试遍历列表并更新数据框中单元格的值。其语法是:

for ix in df.index:
    df.loc[ix, 'Test'] = 'My New Value'

where ix is the row position and 'Test' is the column name that you want to update. If you need to add more logic, you could try somthing like:

其中 ix 是行位置,'Test' 是您要更新的列名。如果您需要添加更多逻辑,您可以尝试以下操作:

for ix in df.index:
    row = df.loc[ix]
    if row.myVariable < 100:
         df.loc[ix, 'SomeColumn'] = 'Less than ahundred'
    else:
         df.loc[ix, 'SomeColumn'] = 'ahundred or more'