代码之家  ›  专栏  ›  技术社区  ›  VERBOSE

如何根据坐标列表选择数据帧的某些值?

  •  1
  • VERBOSE  · 技术社区  · 1 年前

    我的输入是一个数据帧和一个坐标列表:

    df = pd.DataFrame({
     'col1': ['A', 'B', 'C', 'A', 'G'],
     'col2': ['B', 'E', 'F', 'F', 'H'],
     'col3': ['C', 'D', 'E', 'A', 'I']})
    
    coords = [(2, 0), (3, 2)]
    
    print(df)
    
      col1 col2 col3
    0    A    B    C
    1    B    E    D
    2    C    F    E
    3    A    F    A
    4    G    H    I
    

    基本上,我正在尝试在中选择一些单元格 df 基于坐标 X Y 我们从列表中获取 coords 。由于我可能需要反转选择,我创建了一个带有布尔值的函数,因此它有两个工作流。到目前为止,我能够做出两个选择中的一个(简单的一个):

    def select(df, coords, inverted=False):
        if inverted is True:
            for c in coords:
                df.iat[c[0], c[1]] = ''
                
        return df
    

    你们能告诉我另一个是怎么做的吗?

    我的预期输出是以下两个之一:

    # inverted = False
      col1 col2 col3
    0             
    1             
    2    C        
    3              A
    4              
    
    # inverted = True
      col1 col2 col3
    0    A    B    C
    1    B    E    D
    2         F    E
    3    A    F    
    4    G    H    I
    
    2 回复  |  直到 1 年前
        1
  •  3
  •   Nick SamSmith1986    1 年前

    如果您将坐标转换为转置坐标的元组,则可以直接将其用作 ndarray 。您可以使用它将新数组中的值设置为 '' 或来自输入数据帧的相应值,取决于的值 inverted :

    def select(df, coords, inverted=False):
        coords = tuple(np.array(coords).T)
        out = data = np.array(df)
        if inverted:
            out[coords] = ''
        else:
            out = np.full(data.shape, '')
            out[coords] = data[coords]
        return pd.DataFrame(out, columns=df.columns)
    
    select(df, coords, True)
    select(df, coords, False)
    

    输出:

      col1 col2 col3
    0    A    B    C
    1    B    E    D
    2         F    E
    3    A    F
    4    G    H    I
    
      col1 col2 col3
    0
    1
    2    C
    3              A
    4
    
        2
  •  1
  •   Andrej Kesely    1 年前

    要从创建新的数据帧 df coords 你可以做到:

    out, coords = np.empty_like(df), np.array(coords)
    out[:] = np.nan
    out[coords[:, 0], coords[:, 1]] = df.to_numpy()[coords[:, 0], coords[:, 1]]
    
    out = pd.DataFrame(data=out, copy=False, columns=df.columns).fillna("")
    print(out)
    

    打印:

      col1 col2 col3
    0               
    1               
    2    C          
    3              A
    4               
    

    相反:

    out, coords = df.to_numpy(), np.array(coords)
    out[coords[:, 0], coords[:, 1]] = ""
    
    out = pd.DataFrame(data=out, copy=False, columns=df.columns)
    print(out)
    

    打印:

      col1 col2 col3
    0    A    B    C
    1    B    E    D
    2         F    E
    3    A    F     
    4    G    H    I