将两个数据帧连接到方阵的数据帧

时间:2017-11-22 02:39:29

标签: python-2.7 pandas

我有两个pandas数据帧,其形状为" n x n"和" m x n" (m

df1 = pd.DataFrame([[0,1,0,1],[1,0,0,1],[0,0,0,1],[1,1,1,0]])
df2 = pd.DataFrame([[1,1,1,0],[1,1,0,1]])

我希望通过连接上面的数据帧来获取方阵的数据帧:

df3 = foo(df1, df2)
print df3.values

这应该像下面的矩阵一样打印。

[[0,1,0,1,1,1],
 [1,0,0,1,1,1],
 [0,0,0,1,1,0],
 [1,1,1,0,0,1],
 [1,1,1,0,0,0],
 [1,1,0,1,0,0]]

连接的逻辑是这样的:

  1. 方阵的左上部分来自df1
  2. 它的右上部分来自df2
  3. 的转置
  4. 左下角部分来自df2
  5. 其余部分(右下部分)的所有元素均为零。
  6. 如何实现上述逻辑(foo方法)?

2 个答案:

答案 0 :(得分:0)

以下是foo的示例:

def foo(_df1,_df2):
    df1 = _df1.reset_index(drop=True) #to make sure the index is ordered
    df2 = _df2.reset_index(drop=True) #to make sure the index is ordered
    df2_transpose = df2.transpose().reset_index(drop=True) #reset the index to match the join below

    df_upper = df1.join(df2_transpose,rsuffix="_") #add suffix for additional columns
    df_upper.columns = [i for i in range(df_upper.shape[1])] #reset column names to int

    df = pd.concat([df_upper,df2]) #fill the bottom left

    df.fillna(0,inplace=True) #fill with 0 the bottom right

    return df

答案 1 :(得分:0)

foo功能:

def foo(df1_data,df2_data):

    df_test = pd.concat([df1_data,df2_data])
    a = np.concatenate((df2_data.values.T,np.zeros(shape = (df_test.values.shape[0] - df_test.values.shape[1],df2_data.values.shape[0]))))
    final_array = np.append(df_test.values,a, axis=1).astype(int)
    df3_data = pd.DataFrame(final_array)

    return df3_data

df3 = foo(df1,df2)