pandas DataFrame对角线

编程入门 行业动态 更新时间:2024-10-28 06:30:53
本文介绍了 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

更多推荐

pandas DataFrame对角线

本文发布于:2023-11-30 10:21:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649635.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对角线   pandas   DataFrame

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!