python-3.x - 基于条件更改行值的 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
并没有改变。知道出了什么问题吗?
解决方案
这一行:
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])
推荐阅读
- python - 用 Python 计算和打印年龄
- java - 如果生成源没有改变,我如何阻止 Maven 重新生成某些东西?
- selenium-webdriver - 我的 XPath 在对话框上定位输入字段,在脚本中不起作用?
- machine-learning - 通过 k-means 传递数据帧时出错
- r - 如何将指示符列转换为连接列(列名)
- c++ - 防止客户端保留 C++ 类返回的指针
- nginx - Kubernetes 在哪里拉取图像,我如何浏览它们/更改它们的拉取源?
- c# - 如果在 WPF 触摸屏应用程序中与另一个形状发生碰撞,则停止 System.Windows.Shapes.Rectangle 惯性
- c - 在 C 中使用指针转置矩阵
- wordpress - 哈希不会保存在 user_meta