【问题标题】:How to vectorize looking up the row index of one dataframe based on conditions from rows in another dataframe如何根据另一个数据帧中行的条件矢量化查找一个数据帧的行索引
【发布时间】:2020-11-18 00:33:46
【问题描述】:

我有两个具有相同列的熊猫数据框,例如

df1 = pd.DataFrame({'A':[0,0,1,1], 'B':[0,1,0,1]})
df2 = pd.DataFrame({'A':[0,1], 'B':[1,1]})

我想从 df1 返回行索引,其中值与 df2 中的行匹配。例如,产生 [1, 3]。我可以通过循环 df2 来做到这一点,但实际上这真的很慢。在 Pandas 中向量化此操作的正确方法是什么?

【问题讨论】:

    标签: pandas vectorization


    【解决方案1】:

    先试试merge

    out = df1.reset_index().merge(df2,how='right')['index']
    Out[63]: 
    0    1
    1    3
    Name: index, dtype: int64
    

    【讨论】:

    • 太棒了!谢谢。
    • @wthrift yw :-) 如果这是您需要的,请考虑接受?
    • 对不起!我还没有问很多问题。
    • @wthrift yw :-) 快乐编码
    猜你喜欢
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多