【问题标题】:Filter Pandas DataFrame with Nested Arrays使用嵌套数组过滤 Pandas DataFrame
【发布时间】:2017-10-08 06:30:33
【问题描述】:

我有一个 pandas 数据框,其中包含一些列中的数组。我想过滤数据框以仅包含在该列的嵌套数组中找到的具有特定值的行。

例如,我有一个类似这样的数据框:

label MODEL_INDEX ARRAY_VAL
ID
0    4   (11.0,  0.0)   
1   65   (11.0, 10.0)   
2   73   (11.0, 10.0)   
3   74   (10.0,  0.0)   
4   79   (11.0,  0.0)   
5   80   (10.0,  0.0)   
6   88   (11.0,  0.0) 

我想过滤数据框以仅在 ARRAY_VAL 下的数组中包含满足某些变量条件(例如包含 10.0)的数据框以获取此信息:

label MODEL_INDEX ARRAY_VAL
ID  
1   65   (11.0, 10.0)   
2   73   (11.0, 10.0)   
3   74   (10.0,  0.0)    
5   80   (10.0,  0.0) 

基本上,寻找类似的东西:

df[df['ARRAY_VAL'] where 10.0 in df['ARRAY_VAL]]

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用.apply在数据框的每一行中搜索列表:

    # creating the dataframe
    df = pd.DataFrame(columns = ['model_idx','array_val'])
    df.model_idx = [4,65,73,74,79,80,88]
    df.array_val = [[11,0],
                    [11,10],
                    [11,10],
                    [10,0],
                    [11,0],
                    [10,0],
                    [11,0]]
    
    # results is a boolean indicating whether the value is found in the list
    results = df.array_val.apply(lambda a: 10 in a)
    
    # filter the dataframe based on the boolean indicator
    df_final = df[results]
    

    过滤后的数据框为:

    In [41]: df_final.head()
    Out[41]: 
       model_idx array_val
    1         65  [11, 10]
    2         73  [11, 10]
    3         74   [10, 0]
    5         80   [10, 0]
    

    【讨论】:

      【解决方案2】:

      我认为apply 是必需的,因为您想为每个元组值x 测试10.0 in x

      df[df['ARRAY_VAL'].apply(lambda x: 10.0 in x)]
      

      【讨论】:

        【解决方案3】:

        首先建立一个索引

        index = []
        for i, row in enumerate(df.ARRAY_VAL):
            if 10.0 in row:
                index.append(i)
        

        然后索引我们在df['ARRAY_VAL']中找到10.0的数据

        >>> df.loc[index]
        
           MODEL_INDEX ARRAY_VAL
        1         65  (11, 10)
        2         73  (11, 10)
        3         74   (10, 0)
        5         80   (10, 0)
        

        【讨论】:

          猜你喜欢
          • 2021-10-29
          • 2020-11-29
          • 1970-01-01
          • 2020-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多