Padding columns of dataframe

Viewed 556

I have 2 dataframes like this,

df1

    0   1   2   3   4   5   category
0   1   2   3   4   5   6   foo
1   4   5   6   5   6   7   bar
2   7   8   9   5   6   7   foo1

and

df2

    0   1   2   category
0   1   2   3   bar
1   4   5   6   foo

Shape of df1 is (3,7) and shape of df2 is (2,4).

I want to reshape df2 to (2,7) (as per first dataframe df1 columns) keeping the last column same.

df2 

    0   1   2  3  4  5  category
0   1   2   3  0  0  0  bar
1   4   5   6  0  0  0  foo
2 Answers

If you want to ensure that dataframe having less columns will pad the columns with zero according to the dataframe having more columns, then you can try DataFrame.align on axis=1 to align the columns of two dataframes keeping the rows unchanged:

df1, df2 = df1.align(df2, axis=1, fill_value=0)

print(df2)

    0  1  2  3  4  5 category
 0  1  2  3  0  0  0      bar
 1  4  5  6  0  0  0      foo
  1. You can use .shape[0] to get the # of rows from each dataframe. and .shape[1] to get the # of columns from each dataframe.
  2. Use these logically with insert to only include the required rows and make the required columns 0:

s1, s2 = (df1.shape[1]), (df2.shape[1])
s = s1-s2
[df2.insert(s-1, s-1, 0) for s in range(s2,s1)]

    0   1   2   3   4   5   category
0   1   2   3   0   0   0   bar
1   4   5   6   0   0   0   foo

Another method using iloc:

s1, s2 = (df1.shape[1] - 1), (df2.shape[1] - 1)
df3 = pd.concat([df2.iloc[:, :-1],
                 df1.iloc[:df2.shape[0]:, s2:s1],
                 df2.iloc[:, -1]], axis=1)
df3.iloc[:, s2:s1] = 0

    0   1   2   3   4   5   category
0   1   2   3   0   0   0   bar
1   4   5   6   0   0   0   foo
Related