【问题标题】:pandas python: adding blank columns to dfpandas python:向df添加空白列
【发布时间】:2015-09-02 13:35:34
【问题描述】:

我正在尝试将 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

我不确定自己做错了什么?

【问题讨论】:

  • 这似乎很浪费,为什么不直接用正确数量的附加列构造一个df,然后concat
  • 我认为问题在于在第三次迭代中代码 barfs 因为虽然您允许重复,但您现在有 2 个带有空字符串的列作为列名,但这会导致内部检查失败,因为它期望一个唯一的要追加的列,但现在找到 2,如果您的列名是唯一的,那么这将起作用,但同样,为什么不构造一个具有正确尺寸的 df 并连接一次
  • @EdChum - 这就是为什么我为每个列名添加一个额外的空格,以便它认为它是独一无二的。
  • 由于我的工作流程,我无法构建具有正确尺寸的 df。
  • 还有其他方法可以将空列添加到现有的 df 吗?

标签: python pandas insert dataframe col


【解决方案1】:

我不会一次插入一列,而是创建一个您想要的维度的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 个名为 '' 的列。

【讨论】:

    【解决方案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('')
    

    【讨论】:

    • 值显示为 NaN,有没有办法使用空白字符串代替?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 2015-09-04
    • 2022-11-04
    相关资源
    最近更新 更多