最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

pandas DataFrame对角线

SEO心得admin38浏览0评论
本文介绍了 pandas DataFrame对角线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

获得平方DataFrame的对角线的有效方法是什么.我希望结果是带有两个级别的Series和MultiIndex,第一个是DataFrame的索引,第二个级别是DataFrame的列.

What is an efficient way to get the diagonal of a square DataFrame. I would expect the result to be a Series with a MultiIndex with two levels, the first being the index of the DataFrame the second level being the columns of the 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

推荐答案

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

If you don't mind using numpy you could use numpy.diag

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

评论列表(0)

  1. 暂无评论