numpy 如何找到相同的行从一个2D数组到另一个2D数组的位置?

w6mmgewl  于 2023-10-19  发布在  其他
关注(0)|答案(2)|浏览(140)
import numpy as np

# Create two sample dataframes
df1 = np.array([[0.000000,0.000000,0.000000],
[0.090000,0.000000,0.000000],
[0.190000,0.000000,0.000000],
[0.280000,0.000000,0.000000],
[0.380000,0.000000,0.000000],
[0.470000,0.000000,0.000000],
[0.570000,0.000000,0.000000],
[0.660000,0.000000,0.000000],
[0.760000,0.000000,0.000000],
[0.850000,0.000000,0.000000]])

df2 = np.array([[0.470000,0.000000,0.000000],
[0.570000,0.000000,0.000000],
[0.660000,0.000000,0.000000],
[0.760000,0.000000,0.000000],
[0.850000,0.000000,0.000000]
])

df3 = np.where(np.isclose(df1[:, np.newaxis], df2))[0]

print(df3)

我想在df1中找到df2的位置,正确答案是[5, 6, 7, 8, 9],但python输出是[0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9],这没有意义。我怎样才能改变代码找到df2在df1中的正确位置?

7gyucuyw

7gyucuyw1#

如果你只想匹配非零值,你可以删除它们:

np.where(np.isclose(np.where(df1!=0, df1, np.nan)[:, None], df2))[0]

输出量:

array([5, 6, 7, 8, 9])

如果您想要完全匹配,包括零(每行),您可以使用:用途:

out = np.where(np.isclose(df1[:, None], df2).all(2))[0]

输出:array([5, 6, 7, 8, 9])

yvt65v4c

yvt65v4c2#

一种完全匹配的方法:

np.argwhere(np.isin(df1, df2).all(axis=1))

array([[0],[5],[6],[7],[8],[9]], dtype=int64)

相关问题