我正在尝试检查 Dataframe“Actual”中记录的每一行的值是否与 Dataframe“Estimate”中同一行下的值匹配。列位置并不重要。该值只需要存在于不同数据帧之间的同一行级别上。如果需要,可以连接/合并数据帧。 我在下面展示我的代码::
Actual=pd.DataFrame([[4,7,2,8,1],[1,5,7,9,8]], columns=['Actual1','Actual2','Actual3','Actual4','Actual5'])
estimate=pd.DataFrame([[1,2,7,9,3],[0,8,2,5,9]], columns=['estimate1','estimate2','estimate3','estimate4','estimate5'])
Actual
Actual1 Actual2 Actual3 Actual4 Actual5
0 4 7 2 8 1
1 1 5 7 9 8
estimate
estimate1 estimate2 estimate3 estimate4 estimate5
0 1 2 7 9 3
1 0 8 2 5 9
我尝试使用 Pandas::
for loop1 in range(1,6,1):
for loop2 in range(1,6,1):
Actual['want'+str(loop1)]=np.where(Actual['Actual'+ str(loop1)] == estimate['estimate' + str(loop2)],1,0)
最后,我想要的输出::
want=pd.DataFrame([[0,1,1,0,1],[0,1,0,1,1]], columns=['want1','want2','want3','want4','want5'])
want
want1 want2 want3 want4 want5
0 0 1 1 0 1
1 0 1 0 1 1
所以,正如我之前提到的,由于数据框“实际”值 4 不存在于数据框“估计”的整个第一行,列“want1”已被分配值 0。再次考虑第一行数据框“实际”第 5 列的值 = 1,因为此值存在于数据框“估计”的同一第一行(列位置无关紧要)列“want5”已分配值 1。
谢谢。
请您参考如下方法:
假设您的Actual 和estimate DataFrame 中的索引相同,一种方法是只使用apply。使用 isin 沿列进行检查.
Actual.apply(lambda x: x.isin(estimate.loc[x.name]), axis=1).astype('int')
这里我们使用 name 属性作为两个 DataFrame 之间的粘合剂。
演示
>>> Actual.apply(lambda x: x.isin(estimate.loc[x.name]), axis=1).astype('int')
Actual1 Actual2 Actual3 Actual4 Actual5
0 0 1 1 0 1
1 0 1 0 1 1
