【问题标题】:Filter rows which contain a list with continous values in a pandas dataframe在 pandas 数据框中过滤包含具有连续值的列表的行
【发布时间】:2019-11-21 05:38:49
【问题描述】:

您好,我有一个如下所示的数据框:

    starttime                     endtime                                        positions
0   2019-05-16 05:34:26.870 2019-05-16 05:34:41.721 [7, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24...
1   2019-05-16 05:33:56.143 2019-05-16 05:34:10.995 [9, 11, 12, 15, 16, 17, 18, 19, 20, 21, 22, 23...
2   2019-05-16 05:33:35.659 2019-05-16 05:33:50.510 [13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 2...
3   2019-05-16 05:33:04.933 2019-05-16 05:33:19.784 [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,...
4   2019-05-16 05:34:11.507 2019-05-16 05:34:26.358 [3, 4, 9, 10, 11, 12, 15, 16, 17, 18, 19, 20, ...

我想获取这样的行,以便列表包含list(range(min(val),max(val))) 形式的连续值。

我试过了

df[df["positions"] == list(range(min(df["positions"],max(df["positions"]))))]

但我得到如下错误:

ValueError:长度必须匹配才能比较

是因为每个列表的长度不同吗?如果是,我该如何解决?

【问题讨论】:

    标签: python pandas dataframe filter


    【解决方案1】:

    一种方法是在列表列上使用.apply

    df['position'].apply(lambda x: x == list(range(min(x), max(x) + 1)))
    

    小例子

    # Example input
    df = pd.DataFrame({'starttime': list(range(3)), 
                       'endtime': list(range(1, 4)), 
                       'positions': None})
    
    # Manually insert lists into the 'positions' column entries
    df.iat[0, 2] = [1, 4, 9]
    df.iat[1, 2] = list(range(6))
    df.iat[2, 2] = list(range(-4, 3))
    
    # Get a boolean Series
    df['positions'].apply(lambda x: x == list(range(min(x), max(x) + 1)))
    
    0    False
    1     True
    2     True
    

    【讨论】:

    • 这里如何使用'apply',我们要过滤数据ryt?不要编辑“职位”列!
    • 啊,很抱歉,我完全误读了您的要求。我刚刚编辑了我的答案。
    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2020-01-18
    • 2017-08-15
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    相关资源
    最近更新 更多