我有两个数据集如下
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
的相同项在运行代码后将是 0
,df1
将是
print(df)
A B C D
10 0 30 0
11 0 31 0
我尝试使用
df1[df2>= 0.5] = 0
答案 0 :(得分:0)
我认为在将 pandas.DataFrame.where()
变成与 df2
相同的形状后,您应该使用 df1
。请理解,如果条件不匹配,df.where()
将替换所有值,因此这就是将 >=
更改为 <
的原因。
df1 = df1.where(df2<0.5, 0)
>>> df1
A B C D
0 10 0 30 0
1 11 0 31 0
如果您在扩展 df2
时遇到问题,可以使用:
df2 = pd.DataFrame([[0, 1, 0, 1]], columns = ['A', 'B', 'C', 'D'])
>>>df2
A B C D
0 0 1 0 1
n = 1 # df1.shape[0] - 1
df2 = df2.append([df2.loc[0,:]]*n,ignore_index=True)
>>> df2
A B C D
0 0 1 0 1
1 0 1 0 1
答案 1 :(得分:0)
由于两个数据帧的列数相同,pandas 数据帧中的 where()
方法可以完成工作。
即
>>> df1.where(df2 < 0.5)
A B C D
0 10.0 NaN 30.0 NaN
1 NaN NaN NaN NaN
默认情况下,如果条件评估为 False
方法中的 where()
,位置将替换为 NaN
而不是 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