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)

   ab  c  d  e  f  g
d  1000000
e  0010000
f  1010000
g  1100000a0000000b0000000
c  0000000

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  1000000
e  0010000
f  1010000
g  1100000
a  0000000
b  0000000
c  0000000

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  0000000
b  0000000
c  0000000
d  1000000
e  0010000
f  1010000
g  1100000

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:

ab  c  d  e  f  g
d  1000000
e  0010000
f  1010000
g  1100000a0000000b0000000
c  0000000

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