Skip to content Skip to sidebar Skip to footer

Vectorised Method To Append Dataframe Rows To Columns And Vice-versa

My dataframe is as follows: df = pd.DataFrame({'a': {'d': 1, 'e': 0, 'f': 1, 'g': 1}, 'b': {'d': 0, 'e': 0, 'f': 0, 'g': 1}, 'c': {'d': 0, 'e'

Solution 1:

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  g
d  1  0  0  0  0  0  0
e  0  0  1  0  0  0  0
f  1  0  1  0  0  0  0
g  1  1  0  0  0  0  0
a  0  0  0  0  0  0  0
b  0  0  0  0  0  0  0
c  0  0  0  0  0  0  0

Solution 2:

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  g
d  1  0  0  0  0  0  0
e  0  0  1  0  0  0  0
f  1  0  1  0  0  0  0
g  1  1  0  0  0  0  0
a  0  0  0  0  0  0  0
b  0  0  0  0  0  0  0
c  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  g
a  0  0  0  0  0  0  0
b  0  0  0  0  0  0  0
c  0  0  0  0  0  0  0
d  1  0  0  0  0  0  0
e  0  0  1  0  0  0  0
f  1  0  1  0  0  0  0
g  1  1  0  0  0  0  0

Solution 3:

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  g
d  1  0  0  0  0  0  0
e  0  0  1  0  0  0  0
f  1  0  1  0  0  0  0
g  1  1  0  0  0  0  0
a  0  0  0  0  0  0  0
b  0  0  0  0  0  0  0
c  0  0  0  0  0  0  0

Post a Comment for "Vectorised Method To Append Dataframe Rows To Columns And Vice-versa"