【问题标题】:Slicing Pandas DataFrame with a Checkerboard Pattern使用棋盘模式对 Pandas DataFrame 进行切片
【发布时间】:2016-06-10 13:13:52
【问题描述】:

如果我有一个 m x n 数据框,我如何仅选择构成棋盘图案上黑色方块的值(请注意,m 可能不等于 n,可能更大、更小或等于另一个)?我试图通过构建一个布尔掩码来掩盖它,但它并不优雅。另请注意,这些值可能并非都是数字的(列或行中可能有文本),因此严格使用 numpy 可能不起作用。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以使用ogrid来create a "checkerboard":

    In [11]: coords = np.ogrid[0:2, 0:3]
    
    In [12]: checkerboard = (coords[0] + coords[1]) % 2 == 0
                                                  # use != for an inverted board
    
    In [13]: checkerboard
    Out[13]:
    array([[ True, False,  True],
           [False,  True, False]], dtype=bool)
    

    考虑到这一点,您可以 NaN 所有其他值(我认为您的意思是“选择”/掩码):

    In [14]: df = pd.DataFrame([[1, 2, 3], [4, 5 ,6]], columns=list('ABC'))
    
    In [15]: df.where(checkerboard)
    Out[15]:
         A    B    C
    0  1.0  NaN  3.0
    1  NaN  5.0  NaN
    

    注意:你也可以用整数做到这一点:

    In [21]: (coords[0] + coords[1]) % 2
    Out[21]:
    array([[0, 1, 0],
           [1, 0, 1]])
    
    In [22]: ~(coords[0] + coords[1]) % 2
    Out[22]:
    array([[1, 0, 1],
           [0, 1, 0]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 2018-06-02
      相关资源
      最近更新 更多