PythonPandas选择依据

2024-04-24 10:38:03 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
2条回答

^{}类似,这里有一个使用^{}-

df1[(df1.values == df2.values[:,None]).all(-1).any(0)]

这个想法是:

1)对""both 'a' and 'b' values""中的both部分使用np.all。你知道吗

2)对"from df1 match any row in df2"中的任何部分使用np.any。你知道吗

3)通过使用None/np.newaxis扩展维度,使用broadcasting以矢量化的方式完成所有这些操作。你知道吗

样本运行-

In [41]: df1
Out[41]: 
   a  b
0  1  4
1  2  5
2  3  6

In [42]: df2  # Modified to add another row : [1,4] for variety
Out[42]: 
   a  b
0  3  4
1  2  5
2  1  6
3  1  4

In [43]: df1[(df1.values == df2.values[:,None]).all(-1).any(0)]
Out[43]: 
   a  b
0  1  4
1  2  5

使用numpy广播

pd.DataFrame((df1.values[:, None] == df2.values).all(2),
             pd.Index(df1.index, name='df1'),
             pd.Index(df2.index, name='df2'))

enter image description here

相关问题 更多 >