考虑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'))
如何将对角线值对齐到列中?
我喜欢这个结果
我已经完成了
pd.DataFrame([np.roll(row, -k) for k, (_, row) in enumerate(df.iterrows())],
df.index, df.columns)
我希望能有更直接的事情。
答案 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'.