add_column
In [1]:
Copied!
# https://tibble.tidyverse.org/reference/add_column.html
from datar import f
from datar.tibble import *
from datar.base import seq
from datar.core.names import NameNonUniqueError
%run nb_helpers.py
nb_header(add_column)
# https://tibble.tidyverse.org/reference/add_column.html
from datar import f
from datar.tibble import *
from datar.base import seq
from datar.core.names import NameNonUniqueError
%run nb_helpers.py
nb_header(add_column)
Try this notebook on binder.
★ add_column¶
Add one or more columns to an existing data frame.¶
Args:¶
_data
: Data frame to append to
*args
: and
**kwargs
: Name-value pairs to add to the data frame
_before
: and
_after
: Column index or name where to add the new columns
(default to add after the last column)
_dtypes
: The dtypes for the new columns, either a uniform dtype or a
dict of dtypes with keys the column names
Returns:¶
The dataframe with the added columns
In [2]:
Copied!
df = tibble(x=seq(1,3), y=seq(3,1))
df >> add_column(z=seq(-1,1), w=0)
df = tibble(x=seq(1,3), y=seq(3,1))
df >> add_column(z=seq(-1,1), w=0)
Out[2]:
x | y | z | w | |
---|---|---|---|---|
<int64> | <int64> | <int64> | <int64> | |
0 | 1 | 3 | -1 | 0 |
1 | 2 | 2 | 0 | 0 |
2 | 3 | 1 | 1 | 0 |
In [3]:
Copied!
df >> add_column(z=seq(-1,1), _before=f.y)
df >> add_column(z=seq(-1,1), _before=f.y)
Out[3]:
x | z | y | |
---|---|---|---|
<int64> | <int64> | <int64> | |
0 | 1 | -1 | 3 |
1 | 2 | 0 | 2 |
2 | 3 | 1 | 1 |
In [4]:
Copied!
# You can't overwrite existing columns
try:
df >> add_column(x = seq(4,6))
except NameNonUniqueError as err:
print(err)
# You can't overwrite existing columns
try:
df >> add_column(x = seq(4,6))
except NameNonUniqueError as err:
print(err)
Names must be unique: x
In [5]:
Copied!
# You can't create new observations
with try_catch():
df >> add_column(z = seq(1,5))
# You can't create new observations
with try_catch():
df >> add_column(z = seq(1,5))
[ValueError] Value has incompatible index.