如何迭代某个列的某些行并更新它们的值。通过应用条件

数据挖掘 Python 熊猫
2022-03-08 17:01:49

我想通过添加 20 来更新期初股票和期末股票的价值dcsDep2 < 3.028512这是数据集的快照:在此处输入图像描述

我试过这段代码:

for(index_label,row_series) in dep1.iterrows():
    while row_series["Closing Stock"]<3.028512:
            dep1.at[index_label,"Closing Stock"]=row_series["Closing Stock"]+22

但没有显示输出。

1个回答

您可以使用df.loc进行选择,然后设置值。看看这个例子并根据你的数据集进行修改。

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a':[1,2,3], 'b':[0.1,0.3,0.9], 'c':[4,5,6]})

In [3]: df
Out[3]: 
   a    b  c
0  1  0.1  4
1  2  0.3  5
2  3  0.9  6

In [4]: df.loc[df['b'] < 0.5, ['a', 'c']] += 20

In [5]: df
Out[5]: 
    a    b   c
0  21  0.1  24
1  22  0.3  25
2   3  0.9   6

此外,将来尝试将数据集中的样本作为值表而不是图像提供,以便更容易重现示例。