pandas python: 向 df 添加空白列

pandas python: adding blank columns to df

我正在尝试向数据框中添加 x 个空白列。

这是我的函数:

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

但是我收到这个错误

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

我不确定我做错了什么?

试试这个:

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('')

我不是一次插入一列,而是创建一个你想要的维度的 df,然后调用 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

关于为什么会出现该错误:

因为你的str不是一个空格,它是一个空字符串:

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

因此,在第 3 次迭代中,它尝试查找该列,预计只有一个列,但实际上有 2 个,因此内部检查失败,因为它现在找到了 2 个名为 '' 的列。