pythondatatablepy-datatable

assign new columns to datatable


How do I assign new columns to a datatable?

Tried this:

DT1 = dt.Frame(A = range(5))
DT1['B'] = [1, 2, 3, 4, 5]

But getting

ValueError: The LHS of the replacement has 1 columns, while the RHS has 5 replacement expressions


Solution

  • With DT[col] = ... syntax you can assign single-column datatable Frames, or numpy arrays, or pandas DataFrames or Series. In your example, you just need to wrap the rhs into a Frame:

    >>> DT1['B'] = dt.Frame([1, 2, 3, 4, 5])
    >>> DT1
       |     A      B
       | int32  int32
    -- + -----  -----
     0 |     0      1
     1 |     1      2
     2 |     2      3
     3 |     3      4
     4 |     4      5
    [5 rows x 2 columns]