首页 > 解决方案 > 根据其他数据框更改数据框中的值

问题描述

我有两个数据集如下

df1 = pd.DataFrame(np.array([[10, 20, 30, 40],
                            [11, 21, 31, 41]]), columns = ['A', 'B', 'C', 'D'])

df2 = pd.DataFrame(np.array([0, 1, 0, 1]).reshape(1, -1), columns =  ['A', 'B', 'C', 'D'])

我想要的是;如果 的 任何一项df2大于0.5,则在运行代码df1后将是0df1

print(df)
A  B  C  D
10 0 30 0
11 0 31 0

我尝试使用

df1[df2>= 0.5] = 0

标签: python

解决方案


由于两个数据帧的列数相同,因此where()pandas 数据帧中的方法可以完成工作。IE

>>> df1.where(df2 < 0.5)

      A   B     C   D
  0  10.0 NaN  30.0 NaN
  1   NaN NaN   NaN NaN

默认情况下,如果条件Falsewhere()方法中评估为,则位置将替换为NaNbut not inplace。我们可以通过将other参数从默认值更改为0并在我们设置的地方进行更改来更改它inplace=True

>>> df1.where(df2 < 0.5, other=0, inplace=True)
>>> df1
    A  B   C  D
0  10  0  30  0
1   0  0   0  0

推荐阅读