pandas python:向d添加空白列

2024-10-02 22:35:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个数据帧中添加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

但我得到了这个错误

^{pr2}$

我不知道我做错了什么?在


Tags: columns数据addnumberdfdefwithfill
2条回答

试试这个:

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不是一个空格,而是一个空字符串:

^{pr2}$

因此,在第3次迭代中,它试图查找列,期望只有一个列,但是有2个列,因此内部检查失败,因为它现在找到了2个名为''的列。在

相关问题 更多 >