匹配两个DataFrame的行和列

时间:2014-04-10 15:27:17

标签: python pandas

例如:

我想重新排列df_1中的行和列,以便它们匹配df_2中的行和列。我知道两个矩阵中的列名和行名都是相同的,两个矩阵的形状都相同。

>>> df_1
      col1  col2  col3  col4
row1     0     1     2     3
row2     4     5     6     7
row3     8     9    10    11
>>> df_2
      col3  col1  col2  col4
row2    24    25    26    27
row3    28    29    30    31
row1    32    33    34    35
>>> df_1_new
      col3  col1  col2  col4  # rows and columns of df_1
row2     6     4     5     7  # are in the same order as in df_2
row3    10     8     9    11
row1     2     0     1     3

我的代码:

col_names_1 = np.array(['col1', 'col2', 'col3', 'col4'])
col_names_2 = np.array(['col3', 'col1', 'col2', 'col4'])

row_names_1 = np.array(['row1', 'row2', 'row3'])
row_names_2 = np.array(['row2', 'row3', 'row1'])

data_1 = np.arange(12).reshape(3,4)
data_2 = np.arange(24,36).reshape(3,4)


df_1 = pd.DataFrame(data=data_1, index=row_names_1, columns=col_names_1)
df_2 = pd.DataFrame(data=data_2, index=row_names_2, columns=col_names_2)

My_solution:

df_1_new = df_1[df_2.columns].T[df_2.index].T 

我觉得说两次转置是多余的,而且我错过了一个更简单的解决方案。还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

这将形成指数的联合

df1, df2 = df1.align(df2)

这将简单地使df1标记为df2

df1 = df1.reindex_like(df2)