我有两个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]]
foo
方法)?
答案 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)