如何在 pandas 数据框上制作矩形矩阵

ozg*_*ral 2 numpy dataframe python-3.x pandas

我有一个以下形式的矩阵(不一定是正方形):

   A    B    C    D
A  0   0.2  0.3  0.5
E 0.2  0.6  0.9  0.2
D 0.5  0.3  0.6   0
F 0.1  0.4  0.5  0.3
Run Code Online (Sandbox Code Playgroud)

我想把它变成一个方阵,如下所示

   A    B    C    D    E    F
A  0   0.2  0.3  0.5  0.2  0.1
B 0.2   0    0   0.3  0.6  0.4
C 0.3   0    0   0.6  0.9  0.5
D 0.5  0.3  0.6   0   0.2  0.3
E 0.2  0.6  0.9  0.2   0    0
F 0.1  0.4  0.5  0.3   0    0
Run Code Online (Sandbox Code Playgroud)

换句话说,我想扩展行和列,使其成为对称方阵(行和列的顺序相同),并且缺失值用 0 填充。

我想应该有一种方法可以使用 pandas 的内置函数轻松/高效地完成此操作,但我不熟悉该包。

为了方便:

df = pd.DataFrame([[0, 0.2, 0.3, 0.5],
                   [0.2, 0.6, 0.9, 0.2],
                   [0.5, 0.3, 0.6, 0],
                   [0.1, 0.4, 0.5, 0.3]],
                   index=['A', 'E', 'D', 'F'],
                   columns=['A', 'B', 'C', 'D'])
Run Code Online (Sandbox Code Playgroud)

n8y*_*der 5

正如您所认为的,您绝对可以在 Pandas 中非常简洁地完成此操作。

\n\n

一种方法是使用非常好的combine_first方法。

\n\n
result = df.combine_first(df.T).fillna(0.0)\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是,在我使用timeit进行的测试中,每个循环的计时时间为 3.62 ms \xc2\xb1 29.2 \xc2\xb5s,这实际上比我为您的方法获得的时间稍慢(每个循环 3.5 ms \xc2\xb1 28.6 \xc2\xb5s)环形)。

\n\n

然而,通过使用更新方法在 Pandas 中更直接地计算这个值,我能够将其降低到 2.04 ms \xc2\xb1 17.2 \xc2\xb5s 每个循环 \xc2\xb5s 每个循环(大约快 1.7 倍)。

\n\n
# Find the combination of both indices\nfull_index = df.index.union(df.columns)\n# Resize the DataFrame to include all the rows and columns\nall_data = df.reindex(labels=full_index, axis=0).reindex(labels=full_index, axis=1)\n# Update any values we have from the transpose \nall_data.update(all_data.T)\n# Fill the missing entries\nresult = all_data.fillna(0.0)\n
Run Code Online (Sandbox Code Playgroud)\n\n

老实说,我无法获得像我想象的那样多的性能改进,但是两个基于 pandas 的版本至少对我来说更具可读性。

\n