Vectorised method to append dataframe rows to columns and vice-versa Vectorised method to append dataframe rows to columns and vice-versa pandas pandas

Vectorised method to append dataframe rows to columns and vice-versa


Here's one way using reindex:

(df.reindex(df.columns.append(df.index),            axis=1,            fill_value =0)  .reindex(df.index.append(df.columns),            axis=0,            fill_value =0))

print(df_new)   a  b  c  d  e  f  gd  1  0  0  0  0  0  0e  0  0  1  0  0  0  0f  1  0  1  0  0  0  0g  1  1  0  0  0  0  0a  0  0  0  0  0  0  0b  0  0  0  0  0  0  0c  0  0  0  0  0  0  0


Use DataFrame.reindex witn columns and index parameter, new values should be created by Index.append:

df1 = df.reindex(columns=df.columns.append(df.index),                  index=df.index.append(df.columns),                  fill_value = 0)print (df1)   a  b  c  d  e  f  gd  1  0  0  0  0  0  0e  0  0  1  0  0  0  0f  1  0  1  0  0  0  0g  1  1  0  0  0  0  0a  0  0  0  0  0  0  0b  0  0  0  0  0  0  0c  0  0  0  0  0  0  0

Or by Index.union:

df1 = df.reindex(columns=df.columns.union(df.index, sort=False),                  index=df.index.union(df.columns, sort=False),                  fill_value = 0)print (df1)   a  b  c  d  e  f  ga  0  0  0  0  0  0  0b  0  0  0  0  0  0  0c  0  0  0  0  0  0  0d  1  0  0  0  0  0  0e  0  0  1  0  0  0  0f  1  0  1  0  0  0  0g  1  1  0  0  0  0  0


Create a dictionary from fromkeys then unpack it, then use assign and T then assign then T:

print(df.assign(**dict.fromkeys(df.index, 0)).T.assign(**dict.fromkeys(df.columns, 0)).T)

Output:

   a  b  c  d  e  f  gd  1  0  0  0  0  0  0e  0  0  1  0  0  0  0f  1  0  1  0  0  0  0g  1  1  0  0  0  0  0a  0  0  0  0  0  0  0b  0  0  0  0  0  0  0c  0  0  0  0  0  0  0