首页 > 解决方案 > 基于条件更改行值的 Python for 循环可以正常工作,但不会更改 pandas 数据帧上的值?

问题描述

我刚刚进入 Python,我正在尝试for-loop在每一行上进行循环,并根据给定条件在每次迭代中随机选择两列并更改它们的值。for-loop作品没有任何问题;但是,结果在dataframe.

一个可重现的例子:

df= pd.DataFrame({'A': [10,40,10,20,10],
                  'B': [10,10,50,40,50],
                  'C': [10,20,10,10,10],
                  'D': [10,30,10,10,50],
                  'E': [10,10,40,10,10],
                  'F': [2,3,2,2,3]})

df:


    A   B   C   D   E   F
0   10  10  10  10  10  2
1   40  10  20  30  10  3
2   10  50  10  10  40  2
3   20  40  10  10  10  2
4   10  50  10  50  10  3

这是我的for-loop;for 循环遍历所有行并检查列 F 上的值是否 = 2;它随机选择两列值为 10 并将它们更改为 100。

for index, i in df.iterrows():
  if i['F'] == 2:
    i[i==10].sample(2, axis=0)+100
    print(i[i==10].sample(2, axis=0)+100)

这是循环的输出:

E    110
C    110
Name: 0, dtype: int64
C    110
D    110
Name: 2, dtype: int64
C    110
D    110
Name: 3, dtype: int64

这是dataframe预期的样子:

df:


    A   B   C   D   E   F
0   10  10  110 10  110 2
1   40  10  20  30  10  3
2   10  50  110 110 40  2
3   20  40  110 110 10  2
4   10  50  10  50  10  3

但是,上的列dataframe并没有改变。知道出了什么问题吗?

标签: python-3.xpandasdataframefor-loop

解决方案


这一行:

i[i==10].sample(2, axis=0)+100

.sample返回一个新的数据框,因此原始数据框 ( df) 根本没有更新。

尝试这个:

for index, i in df.iterrows():
    if i['F'] == 2:
        cond = (i == 10)

        # You can only sample 2 rows if there are at
        # least 2 rows meeting the condition
        if cond.sum() >= 2:
            idx = i[cond].sample(2).index
            i[idx] += 100
            print(i[idx])

推荐阅读