从第一个匹配行上方的主数据帧返回所有行(从辅助数据帧的顶部开始)

时间:2019-02-08 09:18:52

标签: python-3.x pandas dataframe list-comprehension

我有两个如下所述的数据框:

Primary_df:

attach(my_df)
iris_plot <- plot_ly(my_df, 
                     x = ~Sepal.Length, 
                     y = ~Sepal.Width, 
                     z = ~Petal.Length,
                     text = Species, 
                     type = "scatter3d",
                     color = ~Species,
                     colors = c("red","blue","green"),
                     mode = "markers")

次要df:

        Symbol                   Subject   Broadcast Date/Time
0   CUMMINSIND  Financial Result Updates   06-Feb-2019 18:31
1          IGL  Financial Result Updates   06-Feb-2019 17:16
2   MANAPPURAM  Financial Result Updates   06-Feb-2019 16:10
3   MANAPPURAM            Result Updates   06-Feb-2019 16:00
4     JSWSTEEL  Financial Result Updates   06-Feb-2019 15:18

逻辑应检查Secondary_df中Primary_df中的确切匹配行(仅包含1行)并返回Result_df。

我希望Result_df为:

        Symbol                   Subject   Broadcast Date/Time
0   MANAPPURAM  Financial Result Updates   06-Feb-2019 16:10

1 个答案:

答案 0 :(得分:1)

在新列中使用merge,并按iloc进行过滤:

a = Primary_df.assign(A=np.arange(len(Primary_df))).merge(Secondary_df)['A']

df = Primary_df.iloc[:a.iat[0]]
print (df)
       Symbol                   Subject Broadcast Date/Time
0  CUMMINSIND  Financial Result Updates   06-Feb-2019 18:31
1         IGL  Financial Result Updates   06-Feb-2019 17:16

如果得到:

  

IndexError:索引0超出了大小为0的轴0的边界

这意味着没有行匹配,并且需要使用next来获得更通用的解决方案,以返回0来实现不匹配:

df = Primary_df.iloc[: next(iter(a), 0)]