【问题标题】:Delete dataframe timestamps which are in second dataframe intervals删除第二个数据帧间隔中的数据帧时间戳
【发布时间】:2020-03-31 16:55:39
【问题描述】:

给定:两个数据帧的列=(id,时间戳),另一个数据帧列=(id,start_interval,end_interval),id 总是相同的。其中一个由 timetemp sec 组成,另一个只有时间戳间隔。

df_timestamp

    id      timestamp
1   11006   1365       
2   11006   1366       
3   11006   1367
4   11006   1368
5   11006   1369   
...
101 11006   1465
102 11006   1466
103 11006   1467
104 11006   1468
...

df_intervals

    id      start_interval    end_interval
1   11006   1250              1366
2   11006   1369              1455
...
12  11006   1466              1467
13  11006   1620              1950
...

任务:我需要创建新的数据框,其中 df_timestamp ['timestamp'] 值不在 df_intervals 'intervals' 值中或之间。

输出:

new_df

   id     timestamp  
1  11006  1367       
2  11006  1368 
...
77 11006  1465
78 11006  1468
...

我尝试merge() 他们,但这个 dfs 非常大。也尝试添加一些逻辑表达式并失败。合并的情况似乎有效,但需要无限时间才能运行。此外,合并后需要合适的.loc

有没有更优雅、更有效的方法来做到这一点?

【问题讨论】:

    标签: python pandas merge timestamp intervals


    【解决方案1】:

    如果我理解正确,你需要它:

    crit=  df_timestamp.timestamp.isin(df_intervals.start_interval) \
         | df_timestamp.timestamp.isin(df_intervals.end_interval)
    
    df_timestamp.loc[~crit]                                                                                              
    

    编辑:

    #For readablity:
        df_interval, df_timestamp= dfi,dft
    
    
        matched= dft.groupby( lambda idx: \
                               (  dfi.start_interval.le(dft.loc[idx,"timestamp"]) \
                                & dfi.end_interval.ge(dft.loc[idx,"timestamp"])).any() ) \
                        .groups[False]                                                                               
    
        Out:
           df_timestamp.loc[matched]  
    
    index     id  timestamp
    2          3  11006     1367.0
    3          4  11006     1368.0
    5  101 11006   1465        NaN
    6  102 11006   1466        NaN
    7  103 11006   1467        NaN
    8  104 11006   1468        NaN
    

    EDIT2: 先前代码的变体,具有列表理解:

    dft.loc[ [(dfi.start_interval.gt(ts) | dfi.end_interval.lt(ts)).all() for ts in dft.timestamp] ]
    

    【讨论】:

    • 感谢您的回答,但也不能在间隔之间
    • 参见上面的编辑代码。我想知道这个解决方案是否比您的解决方案更快或更“优雅”。
    猜你喜欢
    • 2019-04-28
    • 2022-11-17
    • 1970-01-01
    • 2019-06-22
    • 2022-01-19
    • 2021-05-07
    • 2016-07-17
    • 2020-09-20
    相关资源
    最近更新 更多