【问题标题】:pandas DataFrame diagonalpandas DataFrame 对角线
【发布时间】:2016-09-15 13:39:14
【问题描述】:

什么是获取正方形DataFrame 的对角线的有效方法。我希望结果是SeriesMultiIndex 有两个级别,第一个是DataFrame 的索引,第二个级别是DataFrame 的列。

设置

import pandas as pd
import numpy as np

np.random.seed([3, 1415])
df = pd.DataFrame(np.random.rand(3, 3) * 5,
                  columns = list('abc'),
                  index = list('ABC'),
                  dtype=np.int64
                 )

我想看看这个:

print df.stack().loc[[('A', 'a'), ('B', 'b'), ('C', 'c')]]

A  a    2
B  b    2
C  c    3

【问题讨论】:

    标签: python numpy pandas


    【解决方案1】:

    您还可以在列表推导中使用iat 来获取对角线。

    >>> pd.Series([df.iat[n, n] for n in range(len(df))], index=[df.index, df.columns]) 
    A  a    2
    B  b    2
    C  c    3
    dtype: int64
    

    【讨论】:

      【解决方案2】:

      如果你不介意使用 numpy,你可以使用 numpy.diag

      pd.Series(np.diag(df), index=[df.index, df.columns])
      
      A  a    2
      B  b    2
      C  c    3
      dtype: int64
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        In [16]:
        midx = pd.MultiIndex.from_tuples(list(zip(df.index,df.columns)))
        pd.DataFrame(data=np.diag(df), index=midx)
        
        Out[16]:
             0
        A a  2
        B b  2
        C c  3
        

        np.diag 会将对角线值作为 np 数组提供给您,然后您可以通过压缩索引和列来构造多索引,并将其作为所需索引传递给 DataFrame ctor。

        其实复杂的多索引生成不需要这么复杂:

        In [18]:
        pd.DataFrame(np.diag(df), index=[df.index, df.columns])
        
        Out[18]:
             0
        A a  2
        B b  2
        C c  3
        

        但是johnchase's answer 更整洁

        【讨论】:

        • 你打败了我numpy.diag 是一个很好的解决方案。是否有必要传递一个多索引?这不行吗? pd.Series(np.diag(df), index=[df.index, df.columns])
        • @johnchase 实际上这是一个更好的解决方案,我只是决定按照 OP 的要求去做
        • @johnchase 请提交答案。刚刚运行它并工作
        猜你喜欢
        • 2019-01-02
        • 2022-12-17
        • 2017-04-03
        • 1970-01-01
        • 2014-08-26
        • 2022-10-13
        • 2018-12-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多