pandas python: adding blank columns to df

4.2k views Asked by At

I'm trying to add x number of blank columns to a dataframe.

Here is my function:

def fill_with_bars(df, number=10):
    '''
    Add blank, empty columns to dataframe, at position 0
    '''

    numofcols = len(df.columns)

    while numofcols < number:
        whitespace = ''
        df.insert(0, whitespace, whitespace, allow_duplicates=True)
        whitespace += whitespace
    return df

but I get this error

ValueError: Wrong number of items passed 2, placement implies 1

I'm not sure what I'm doing wrong?

2

There are 2 answers

1
AudioBubble On BEST ANSWER

Try this:

def fill_with_bars(old_df, number=10):
    empty_col = [' '*i for i in range(1,number+1)]
    tmp = df(columns=empty_col)
    return pd.concat([tmp,old_df], axis=1).fillna('')
0
EdChum On

Rather than inserting a column at a time, I'd create a df of the dimensions you desired and then call concat:

In [72]:
def fill_with_bars(df, number=10):
    return pd.concat([pd.DataFrame([],index=df.index, columns=range(10)).fillna(''), df], axis=1)
​
df = pd.DataFrame({'a':np.arange(10), 'b':np.arange(10)})
fill_with_bars(df)

Out[72]:
  0 1 2 3 4 5 6 7 8 9  a  b
0                      0  0
1                      1  1
2                      2  2
3                      3  3
4                      4  4
5                      5  5
6                      6  6
7                      7  7
8                      8  8
9                      9  9

As to why you get that error:

It's because your str is not a single whitespace, it's an empty string:

In [75]:
whitespace = ''
whitespace + whitespace
Out[75]:
''

So on the 3rd iteration, it's trying to lookup the column, expecting there to be only a single column but there are 2 so it failes the internal checks as it now finds 2 columns called ''.