熊猫检查一个多索引列中的值是否在任何列中,不同多索引的同一行
我有以下数据框:
df = pd.DataFrame([[0, 1, 7, 0, 1, 8, 3, 0],
[7, 3, 4, 0, 4, 9, 7, 0]],
columns=pd.MultiIndex.from_product([["first", "second"],
["A", "B", "C", "D"]]))
print(df)
first second
A B C D A B C D
0 0 1 7 0 1 8 3 0
1 7 3 4 0 4 9 7 0
我想检查 first 中的值是否存在于 second 的任何列中。只应比较同一行。
生成的数据框应如下所示:
A B C D
0 True True False True
1 True False True True
这样做的最佳方法是什么?我已经玩过 df["first"].isin(df["second"] 但它只将 A 与 A、B 与 B 进行比较,......也尝试将它与 .any() 结合使用,但我不能似乎使它起作用。
非常感谢您的帮助!
先感谢您。
回答
麻木广播
np.any(df['first'].T.values[:, :, None] == df['second'].values, axis=-1).T
array([[ True, True, False, True],
[ True, False, True, True]])
- Thanks to you and all the others that answered! I accepted this answer as it seemed to perform the best on my dataset. This answer took 0.0022 seconds, @Quang Hoang's 0.0125 seconds and ashkangh's 1.9600 seconds.
- This is a GREAT solution, very well formed, you ROCK Shubham cheers 🙂
回答
另一种解决方案:
df['first'].apply(lambda x: x.isin(df.loc[x.name, ('second')]), axis=1)
输出:
A B C D
0 True True False True
1 True False True True