【问题标题】:Stack a square DataFrame to only keep the upper/lower triangle堆叠方形 DataFrame 以仅保留上/下三角形
【发布时间】:2017-08-11 09:13:01
【问题描述】:

我在pandas 中有一个对称正方形DataFrame

a = np.random.rand(3, 3)
a = (a + a.T)/2
np.fill_diagonal(a, 1.)
a = pd.DataFrame(a)

看起来像这样:

          0         1         2
0  1.000000  0.747064  0.357616
1  0.747064  1.000000  0.631622
2  0.357616  0.631622  1.000000

如果我应用stack 方法,我会得到很多冗余信息(包括我不感兴趣的对角线):

0  0    1.000000
   1    0.747064
   2    0.357616
1  0    0.747064
   1    1.000000
   2    0.631622
2  0    0.357616
   1    0.631622
   2    1.000000

有没有办法只使用“纯”pandas 获得下(或上)三角形?

1  0    0.747064
2  0    0.357616
   1    0.631622

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    你可以使用mask

    In [278]: a.mask(np.triu(np.ones(a.shape)).astype(bool)).stack()
    Out[278]:
    1  0    0.747064
    2  0    0.357616
       1    0.631622
    dtype: float64
    

    或使用where

    In [285]: a.where(np.tril(np.ones(a.shape), -1).astype(bool)).stack()
    Out[285]:
    1  0    0.747064
    2  0    0.357616
       1    0.631622
    dtype: float64
    

    【讨论】:

      【解决方案2】:

      我能想到的最简单的方法是将上(或下)三角形强制为 NaN,因为默认情况下 stack 方法不会包含 NaN:

      a.values[np.triu_indices_from(a, 0)] = np.nan
      a.stack()
      

      给出:

      1  0    0.747064
      2  0    0.357616
         1    0.631622
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多