Home > front end >  Adding Dummy Column If Number of Column is less than number of rows
Adding Dummy Column If Number of Column is less than number of rows

Time:12-04

I have non-square table which look like this:

input:
        A   B   C
    0   4   2   5 
    1   2   6   8
    2   8   3   4
    3   4   2   5
    4   3   6   7
    5   7   3   8

the output should be like this

output:
        A   B   C   d1   d2   d3
    0   4   2   5   0    0    0
    1   2   6   8   0    0    0
    2   8   3   4   0    0    0
    3   4   2   5   0    0    0
    4   3   6   7   0    0    0
    5   7   3   8   0    0    0

Since the number of columns is 3 and the rows are 6, therefore I want to create dummy columns as much as the number of rows. So in this case, I need 3 columns more, with all 0 values on them. And I also want the column name is "d1", "d2", "d3", etc. Could anyone help me on this matter? Thanks in advance!

CodePudding user response:

You can do reindex

out = df.reindex(columns = df.columns.to_list() [*range(df.shape[0]-df.shape[1])],fill_value=0)
Out[65]: 
   A  B  C  0  1  2
0  4  2  5  0  0  0
1  2  6  8  0  0  0
2  8  3  4  0  0  0
3  4  2  5  0  0  0
4  3  6  7  0  0  0
5  7  3  8  0  0  0
  • Related