将数据框对角线对齐到列中?

时间:2016-10-21 04:59:09

标签: python pandas numpy dataframe diagonal

考虑pd.DataFrame df

df = pd.DataFrame([
        [1, 2, 3, 4, 5],
        [5, 1, 2, 3, 4],
        [4, 5, 1, 2, 3],
        [3, 4, 5, 1, 2],
        [2, 3, 4, 5, 1]
    ], list('abcde'), list('ABCDE'))

如何将对角线值对齐到列中?

我喜欢这个结果

enter image description here

我已经完成了

pd.DataFrame([np.roll(row, -k) for k, (_, row) in enumerate(df.iterrows())],
             df.index, df.columns)

我希望能有更直接的事情。

2 个答案:

答案 0 :(得分:4)

您可以使用numpy solution - 对于shift,使用与Series相同的反向DataFrame长度(如果DataFrame具有非数字和非单调索引,则它也很好用) :

A = df.values
r = pd.Series(range(len(df)))[::-1] + 1

rows, column_indices = np.ogrid[:A.shape[0], :A.shape[1]]

r[r < 0] += A.shape[1]
column_indices = column_indices - r[:,np.newaxis]

result = A[rows, column_indices]
print (pd.DataFrame(result, df.index, df.columns))
   A  B  C  D  E
a  1  2  3  4  5
b  1  2  3  4  5
c  1  2  3  4  5
d  1  2  3  4  5
e  1  2  3  4  5

答案 1 :(得分:2)

这是使用NumPy broadcasting -

的另一种方法
[ts] Class 'MyClass' incorrectly implements interface 'InterfaceMyClass'.
       Property 'FromJSON' is missing in type 'MyClass'.