# Tabular core


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Initial preprocessing

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L20"
target="_blank" style="float:right; font-size:smaller">source</a>

### make_date

``` python
def make_date(
    df, date_field
):
```

*Make sure `df[date_field]` is of the right date type.*

``` python
df = pd.DataFrame({'date': ['2019-12-04', '2019-11-29', '2019-11-15', '2019-10-24']})
make_date(df, 'date')
test_eq(df['date'].dtype, np.dtype('datetime64[us]'))
```

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L28"
target="_blank" style="float:right; font-size:smaller">source</a>

### add_datepart

``` python
def add_datepart(
    df, field_name, prefix:NoneType=None, drop:bool=True, time:bool=False
):
```

*Helper function that adds columns relevant to a date in the column
`field_name` of `df`.*

For example if we have a series of dates we can then generate features
such as `Year`, `Month`, `Day`, `Dayofweek`, `Is_month_start`, etc as
shown below:

``` python
df = pd.DataFrame({'date': ['2019-12-04', None, '2019-11-15', '2019-10-24']})
df = add_datepart(df, 'date')
df.head()
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">Year</th>
<th data-quarto-table-cell-role="th">Month</th>
<th data-quarto-table-cell-role="th">Week</th>
<th data-quarto-table-cell-role="th">Day</th>
<th data-quarto-table-cell-role="th">Dayofweek</th>
<th data-quarto-table-cell-role="th">Dayofyear</th>
<th data-quarto-table-cell-role="th">Is_month_end</th>
<th data-quarto-table-cell-role="th">Is_month_start</th>
<th data-quarto-table-cell-role="th">Is_quarter_end</th>
<th data-quarto-table-cell-role="th">Is_quarter_start</th>
<th data-quarto-table-cell-role="th">Is_year_end</th>
<th data-quarto-table-cell-role="th">Is_year_start</th>
<th data-quarto-table-cell-role="th">Elapsed</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>2019.0</td>
<td>12.0</td>
<td>49.0</td>
<td>4.0</td>
<td>2.0</td>
<td>338.0</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>1575417.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>NaN</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>2019.0</td>
<td>11.0</td>
<td>46.0</td>
<td>15.0</td>
<td>4.0</td>
<td>319.0</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>1573776.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>2019.0</td>
<td>10.0</td>
<td>43.0</td>
<td>24.0</td>
<td>3.0</td>
<td>297.0</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>False</td>
<td>1571875.0</td>
</tr>
</tbody>
</table>

</div>

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L57"
target="_blank" style="float:right; font-size:smaller">source</a>

### add_elapsed_times

``` python
def add_elapsed_times(
    df, field_names, date_field, base_field
):
```

*Add in `df` for each event in `field_names` the elapsed time according
to `date_field` grouped by `base_field`*

``` python
# chkstyle: skip
df = pd.DataFrame({'date': ['2019-12-04', '2019-11-29', '2019-11-15', '2019-10-24'],
                   'event': [False, True, False, True], 'base': [1,1,2,2]})
df = add_elapsed_times(df, ['event'], 'date', 'base')
df.head()
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">date</th>
<th data-quarto-table-cell-role="th">event</th>
<th data-quarto-table-cell-role="th">base</th>
<th data-quarto-table-cell-role="th">Afterevent</th>
<th data-quarto-table-cell-role="th">Beforeevent</th>
<th data-quarto-table-cell-role="th">event_bw</th>
<th data-quarto-table-cell-role="th">event_fw</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>2019-12-04</td>
<td>False</td>
<td>1</td>
<td>5</td>
<td>0</td>
<td>1.0</td>
<td>0.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>2019-11-29</td>
<td>True</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1.0</td>
<td>1.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>2019-11-15</td>
<td>False</td>
<td>2</td>
<td>22</td>
<td>0</td>
<td>1.0</td>
<td>0.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>2019-10-24</td>
<td>True</td>
<td>2</td>
<td>0</td>
<td>0</td>
<td>1.0</td>
<td>1.0</td>
</tr>
</tbody>
</table>

</div>

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L83"
target="_blank" style="float:right; font-size:smaller">source</a>

### cont_cat_split

``` python
def cont_cat_split(
    df, max_card:int=20, dep_var:NoneType=None
):
```

*Helper function that returns column names of cont and cat variables
from given `df`.*

This function works by determining if a column is continuous or
categorical based on the cardinality of its values. If it is above the
`max_card` parameter (or a `float` datatype) then it will be added to
the `cont_names` else `cat_names`. An example is below:

``` python
# chkstyle: skip
# Example with simple numpy types
df = pd.DataFrame({'cat1': [1, 2, 3, 4], 'cont1': [1., 2., 3., 2.], 'cat2': ['a', 'b', 'b', 'a'],
                   'i8': pd.Series([1, 2, 3, 4], dtype='int8'),
                   'u8': pd.Series([1, 2, 3, 4], dtype='uint8'),
                   'f16': pd.Series([1, 2, 3, 4], dtype='float16'),
                   'y1': [1, 0, 1, 0], 'y2': [2, 1, 1, 0]})
cont_names, cat_names = cont_cat_split(df)
```

    cont_names: ['cont1', 'f16']
    cat_names: ['cat1', 'cat2', 'i8', 'u8', 'y1', 'y2']`

``` python
# chkstyle: skip
# Example with pandas types and generated columns
df = pd.DataFrame({'cat1': pd.Series(['l','xs','xl','s'], dtype='category'),
                    'ui32': pd.Series([1, 2, 3, 4], dtype='UInt32'),
                    'i64': pd.Series([1, 2, 3, 4], dtype='Int64'),
                    'f16': pd.Series([1, 2, 3, 4], dtype='Float64'),
                    'd1_date': ['2021-02-09', None, '2020-05-12', '2020-08-14'],
                    })
df = add_datepart(df, 'd1_date', drop=False)
df['cat1'] = df['cat1'].cat.set_categories(['xl','l','m','s','xs'], ordered=True)
cont_names, cat_names = cont_cat_split(df, max_card=0)
```

    cont_names: ['ui32', 'i64', 'f16', 'd1_Year', 'd1_Month', 'd1_Week', 'd1_Day', 'd1_Dayofweek', 'd1_Dayofyear', 'd1_Elapsed']
    cat_names: ['cat1', 'd1_date', 'd1_Is_month_end', 'd1_Is_month_start', 'd1_Is_quarter_end', 'd1_Is_quarter_start', 'd1_Is_year_end', 'd1_Is_year_start']

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L97"
target="_blank" style="float:right; font-size:smaller">source</a>

### df_shrink_dtypes

``` python
def df_shrink_dtypes(
    df, skip:list=[], obj2cat:bool=True, int2uint:bool=False
):
```

*Return any possible smaller data types for DataFrame columns. Allows
`object`-\>`category`, `int`-\>`uint`, and exclusion.*

For example we will make a sample `DataFrame` with `int`, `float`,
`bool`, and `object` datatypes:

``` python
# chkstyle: skip
df = pd.DataFrame({'i': [-100, 0, 100], 'f': [-100.0, 0.0, 100.0], 'e': [True, False, True],
                   'date':['2019-12-04','2019-11-29','2019-11-15',]})
df.dtypes
```

    i         int64
    f       float64
    e          bool
    date        str
    dtype: object

We can then call
[`df_shrink_dtypes`](https://docs.fast.ai/tabular/tabular.core.html#df_shrink_dtypes)
to find the smallest possible datatype that can support the data:

``` python
dt = df_shrink_dtypes(df)
dt
```

    {'i': dtype('int8'), 'f': dtype('float32'), 'date': 'category'}

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L126"
target="_blank" style="float:right; font-size:smaller">source</a>

### df_shrink

``` python
def df_shrink(
    df, skip:list=[], obj2cat:bool=True, int2uint:bool=False
):
```

*Reduce DataFrame memory usage, by casting to smaller types returned by
[`df_shrink_dtypes()`](https://docs.fast.ai/tabular/tabular.core.html#df_shrink_dtypes).*

`df_shrink(df)` attempts to make a DataFrame uses less memory, by fit
numeric columns into smallest datatypes. In addition:

- `boolean`, `category`, `datetime64[ns]` dtype columns are ignored.
- ‘object’ type columns are categorified, which can save a lot of memory
  in large dataset. It can be turned off by `obj2cat=False`.
- `int2uint=True`, to fit `int` types to `uint` types, if all data in
  the column is \>= 0.
- columns can be excluded by name using `excl_cols=['col1','col2']`.

To get only new column data types without actually casting a DataFrame,
use
[`df_shrink_dtypes()`](https://docs.fast.ai/tabular/tabular.core.html#df_shrink_dtypes)
with all the same parameters for
[`df_shrink()`](https://docs.fast.ai/tabular/tabular.core.html#df_shrink).

``` python
# chkstyle: skip
df = pd.DataFrame({'i': [-100, 0, 100], 'f': [-100.0, 0.0, 100.0], 'u':[0, 10,254],
                  'date':['2019-12-04','2019-11-29','2019-11-15']})
df2 = df_shrink(df, skip=['date'])
```

Let’s compare the two:

``` python
df.dtypes
```

    i         int64
    f       float64
    u         int64
    date        str
    dtype: object

``` python
df2.dtypes
```

    i          int8
    f       float32
    u         int16
    date        str
    dtype: object

We can see that the datatypes changed, and even further we can look at
their relative memory usages:

    Initial Dataframe: 228 bytes
    Reduced Dataframe: 177 bytes

Here’s another example using the `ADULT_SAMPLE` dataset:

``` python
path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv')
new_df = df_shrink(df, int2uint=True)
```

    Initial Dataframe: 3.907452 megabytes
    Reduced Dataframe: 0.814989 megabytes

We reduced the overall memory used by 79%!

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L144"
target="_blank" style="float:right; font-size:smaller">source</a>

### Tabular

``` python
def Tabular(
    df, procs:NoneType=None, cat_names:NoneType=None, cont_names:NoneType=None, y_names:NoneType=None,
    y_block:NoneType=None, splits:NoneType=None, do_setup:bool=True, device:NoneType=None, inplace:bool=False,
    reduce_memory:bool=True
):
```

*A `DataFrame` wrapper that knows which cols are cont/cat/y, and returns
rows in `__getitem__`*

- `df`: A `DataFrame` of your data
- `cat_names`: Your categorical `x` variables
- `cont_names`: Your continuous `x` variables
- `y_names`: Your dependent `y` variables
  - Note: Mixed y’s such as Regression and Classification is not
    currently supported, however multiple regression or classification
    outputs is
- `y_block`: How to sub-categorize the type of `y_names`
  ([`CategoryBlock`](https://docs.fast.ai/data/data.block.html#categoryblock)
  or
  [`RegressionBlock`](https://docs.fast.ai/data/data.block.html#regressionblock))
- `splits`: How to split your data
- `do_setup`: A parameter for if
  [`Tabular`](https://docs.fast.ai/tabular/tabular.core.html#tabular)
  will run the data through the `procs` upon initialization
- `device`: `cuda` or `cpu`
- `inplace`: If `True`,
  [`Tabular`](https://docs.fast.ai/tabular/tabular.core.html#tabular)
  will not keep a separate copy of your original `DataFrame` in memory.
  You should ensure `pd.options.mode.chained_assignment` is `None`
  before setting this
- `reduce_memory`: `fastai` will attempt to reduce the overall memory
  usage by the inputted `DataFrame` with
  [`df_shrink`](https://docs.fast.ai/tabular/tabular.core.html#df_shrink)

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L199"
target="_blank" style="float:right; font-size:smaller">source</a>

### TabularPandas

``` python
def TabularPandas(
    df, procs:NoneType=None, cat_names:NoneType=None, cont_names:NoneType=None, y_names:NoneType=None,
    y_block:NoneType=None, splits:NoneType=None, do_setup:bool=True, device:NoneType=None, inplace:bool=False,
    reduce_memory:bool=True
):
```

*A [`Tabular`](https://docs.fast.ai/tabular/tabular.core.html#tabular)
object with transforms*

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L221"
target="_blank" style="float:right; font-size:smaller">source</a>

### TabularProc

``` python
def TabularProc(
    enc:NoneType=None, dec:NoneType=None, split_idx:NoneType=None, order:NoneType=None
):
```

*Base class to write a non-lazy tabular processor for dataframes*

These transforms are applied as soon as the data is available rather
than as data is called from the
[`DataLoader`](https://docs.fast.ai/data/data.load.html#dataloader)

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L238"
target="_blank" style="float:right; font-size:smaller">source</a>

### Categorify

``` python
def Categorify(
    enc:NoneType=None, dec:NoneType=None, split_idx:NoneType=None, order:NoneType=None
):
```

*Transform the categorical variables to something similar to
`pd.Categorical`*

While visually in the `DataFrame` you will not see a change, the classes
are stored in `to.procs.categorify` as we can see below on a dummy
`DataFrame`:

``` python
df = pd.DataFrame({'a':[0,1,2,0,2]})
to = TabularPandas(df, Categorify, 'a')
to.show()
```

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">a</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>1</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>2</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>2</td>
</tr>
</tbody>
</table>

Each column’s unique values are stored in a dictionary of
`column:[values]`:

``` python
cat = to.procs.categorify
cat.classes
```

    {'a': ['#na#', np.int8(0), np.int8(1), np.int8(2)]}

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L285"
target="_blank" style="float:right; font-size:smaller">source</a>

### FillStrategy

``` python
def FillStrategy(
    *args, **kwargs
):
```

*Namespace containing the various filling strategies.*

Currently, filling with the `median`, a `constant`, and the `mode` are
supported.

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L292"
target="_blank" style="float:right; font-size:smaller">source</a>

### FillMissing

``` python
def FillMissing(
    fill_strategy:function=median, add_col:bool=True, fill_vals:NoneType=None
):
```

*Fill the missing values in continuous columns.*

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L316"
target="_blank" style="float:right; font-size:smaller">source</a>

### ReadTabBatch

``` python
def ReadTabBatch(
    to
):
```

*Transform
[`TabularPandas`](https://docs.fast.ai/tabular/tabular.core.html#tabularpandas)
values into a `Tensor` with the ability to decode*

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L342"
target="_blank" style="float:right; font-size:smaller">source</a>

### TabDataLoader

``` python
def TabDataLoader(
    dataset, # Map- or iterable-style dataset from which to load the data
    bs:int=16, # Size of batch
    shuffle:bool=False, # Whether to shuffle data
    after_batch:NoneType=None,
    num_workers:int=0, # Number of CPU cores to use in parallel (default: All available up to 16)
    *, verbose:bool=False, # Whether to print verbose logs
    do_setup:bool=True, # Whether to run `setup()` for batch transform(s)
    pin_memory:bool=False, timeout:int=0, batch_size:NoneType=None, drop_last:bool=False, indexed:NoneType=None,
    n:NoneType=None, device:NoneType=None, persistent_workers:bool=False, pin_memory_device:str='',
    wif:NoneType=None, before_iter:NoneType=None, after_item:NoneType=None, before_batch:NoneType=None,
    after_iter:NoneType=None, create_batches:NoneType=None, create_item:NoneType=None, create_batch:NoneType=None,
    retain:NoneType=None, get_idxs:NoneType=None, sample:NoneType=None, shuffle_fn:NoneType=None,
    do_batch:NoneType=None
):
```

*A transformed
[`DataLoader`](https://docs.fast.ai/data/data.load.html#dataloader) for
Tabular data*

------------------------------------------------------------------------

<a
href="https://github.com/fastai/fastai/blob/main/fastai/tabular/core.py#L356"
target="_blank" style="float:right; font-size:smaller">source</a>

### TabWeightedDL

``` python
def TabWeightedDL(
    dataset, # Map- or iterable-style dataset from which to load the data
    bs:int=16, # Size of batch
    wgts:NoneType=None, shuffle:bool=False, # Whether to shuffle data
    after_batch:NoneType=None,
    num_workers:int=0, # Number of CPU cores to use in parallel (default: All available up to 16)
    *, verbose:bool=False, # Whether to print verbose logs
    do_setup:bool=True, # Whether to run `setup()` for batch transform(s)
    pin_memory:bool=False, timeout:int=0, batch_size:NoneType=None, drop_last:bool=False, indexed:NoneType=None,
    n:NoneType=None, device:NoneType=None, persistent_workers:bool=False, pin_memory_device:str='',
    wif:NoneType=None, before_iter:NoneType=None, after_item:NoneType=None, before_batch:NoneType=None,
    after_iter:NoneType=None, create_batches:NoneType=None, create_item:NoneType=None, create_batch:NoneType=None,
    retain:NoneType=None, get_idxs:NoneType=None, sample:NoneType=None, shuffle_fn:NoneType=None,
    do_batch:NoneType=None
):
```

*A transformed
[`DataLoader`](https://docs.fast.ai/data/data.load.html#dataloader) for
Tabular Weighted data*

## Integration example

For a more in-depth explanation, see the [tabular
tutorial](http://docs.fast.ai/tutorial.tabular.html)

``` python
path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv')
df_main,df_test = df.iloc[:10000].copy(),df.iloc[10000:].copy()
df_test.drop('salary', axis=1, inplace=True)
df_main.head()
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">age</th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">education-num</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">sex</th>
<th data-quarto-table-cell-role="th">capital-gain</th>
<th data-quarto-table-cell-role="th">capital-loss</th>
<th data-quarto-table-cell-role="th">hours-per-week</th>
<th data-quarto-table-cell-role="th">native-country</th>
<th data-quarto-table-cell-role="th">salary</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>49</td>
<td>Private</td>
<td>101320</td>
<td>Assoc-acdm</td>
<td>12.0</td>
<td>Married-civ-spouse</td>
<td>NaN</td>
<td>Wife</td>
<td>White</td>
<td>Female</td>
<td>0</td>
<td>1902</td>
<td>40</td>
<td>United-States</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>44</td>
<td>Private</td>
<td>236746</td>
<td>Masters</td>
<td>14.0</td>
<td>Divorced</td>
<td>Exec-managerial</td>
<td>Not-in-family</td>
<td>White</td>
<td>Male</td>
<td>10520</td>
<td>0</td>
<td>45</td>
<td>United-States</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>38</td>
<td>Private</td>
<td>96185</td>
<td>HS-grad</td>
<td>NaN</td>
<td>Divorced</td>
<td>NaN</td>
<td>Unmarried</td>
<td>Black</td>
<td>Female</td>
<td>0</td>
<td>0</td>
<td>32</td>
<td>United-States</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>38</td>
<td>Self-emp-inc</td>
<td>112847</td>
<td>Prof-school</td>
<td>15.0</td>
<td>Married-civ-spouse</td>
<td>Prof-specialty</td>
<td>Husband</td>
<td>Asian-Pac-Islander</td>
<td>Male</td>
<td>0</td>
<td>0</td>
<td>40</td>
<td>United-States</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>42</td>
<td>Self-emp-not-inc</td>
<td>82297</td>
<td>7th-8th</td>
<td>NaN</td>
<td>Married-civ-spouse</td>
<td>Other-service</td>
<td>Wife</td>
<td>Black</td>
<td>Female</td>
<td>0</td>
<td>0</td>
<td>50</td>
<td>United-States</td>
<td>&lt;50k</td>
</tr>
</tbody>
</table>

</div>

``` python
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']
cont_names = ['age', 'fnlwgt', 'education-num']
procs = [Categorify, FillMissing, Normalize]
splits = RandomSplitter()(range_of(df_main))
```

``` python
to = TabularPandas(df_main, procs, cat_names, cont_names, y_names="salary", splits=splits)
```

``` python
dls = to.dataloaders()
dls.valid.show_batch()
```

    /Users/jhoward/aai-ws/fastai/fastai/torch_core.py:154: UserWarning: The given NumPy array is not writable, and PyTorch does not support non-writable tensors. This means writing to this tensor will result in undefined behavior. You may want to copy the array to protect its data or make it writable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at /Users/runner/work/pytorch/pytorch/pytorch/torch/csrc/utils/tensor_numpy.cpp:212.)
      else as_tensor(x.values, **kwargs) if isinstance(x, (pd.Series, pd.DataFrame))

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">education-num_na</th>
<th data-quarto-table-cell-role="th">age</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education-num</th>
<th data-quarto-table-cell-role="th">salary</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>State-gov</td>
<td>Bachelors</td>
<td>Never-married</td>
<td>Prof-specialty</td>
<td>Not-in-family</td>
<td>White</td>
<td>False</td>
<td>23.000000</td>
<td>287987.999279</td>
<td>13.0</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>State-gov</td>
<td>Some-college</td>
<td>Never-married</td>
<td>Tech-support</td>
<td>Unmarried</td>
<td>Black</td>
<td>False</td>
<td>32.000000</td>
<td>131587.998019</td>
<td>10.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>Private</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Other-service</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>58.000000</td>
<td>183810.000021</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>Self-emp-inc</td>
<td>Some-college</td>
<td>Married-civ-spouse</td>
<td>Sales</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>83.999998</td>
<td>172906.999298</td>
<td>10.0</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>Local-gov</td>
<td>Bachelors</td>
<td>Never-married</td>
<td>Sales</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>31.000000</td>
<td>128016.002079</td>
<td>13.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5</td>
<td>Private</td>
<td>Some-college</td>
<td>Never-married</td>
<td>Adm-clerical</td>
<td>Not-in-family</td>
<td>White</td>
<td>False</td>
<td>22.000001</td>
<td>58915.997617</td>
<td>10.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>?</td>
<td>11th</td>
<td>Never-married</td>
<td>?</td>
<td>Not-in-family</td>
<td>White</td>
<td>False</td>
<td>26.000000</td>
<td>176966.999519</td>
<td>7.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">7</td>
<td>Private</td>
<td>Bachelors</td>
<td>Married-civ-spouse</td>
<td>Prof-specialty</td>
<td>Other-relative</td>
<td>Asian-Pac-Islander</td>
<td>False</td>
<td>23.999999</td>
<td>86744.998003</td>
<td>13.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">8</td>
<td>Private</td>
<td>Some-college</td>
<td>Never-married</td>
<td>Other-service</td>
<td>Not-in-family</td>
<td>White</td>
<td>False</td>
<td>38.000000</td>
<td>123833.001583</td>
<td>10.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">9</td>
<td>Private</td>
<td>11th</td>
<td>Married-civ-spouse</td>
<td>Farming-fishing</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>35.000000</td>
<td>168322.000103</td>
<td>7.0</td>
<td>&lt;50k</td>
</tr>
</tbody>
</table>

``` python
to.show()
```

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">education-num_na</th>
<th data-quarto-table-cell-role="th">age</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education-num</th>
<th data-quarto-table-cell-role="th">salary</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">3564</td>
<td>Self-emp-not-inc</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Craft-repair</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>50.0</td>
<td>124793.0</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5802</td>
<td>Private</td>
<td>HS-grad</td>
<td>Never-married</td>
<td>Adm-clerical</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>30.0</td>
<td>205204.0</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1087</td>
<td>Self-emp-not-inc</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Farming-fishing</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>55.0</td>
<td>149168.0</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1239</td>
<td>Private</td>
<td>HS-grad</td>
<td>Never-married</td>
<td>Other-service</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>25.0</td>
<td>104193.0</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2234</td>
<td>Private</td>
<td>HS-grad</td>
<td>Never-married</td>
<td>Handlers-cleaners</td>
<td>Other-relative</td>
<td>White</td>
<td>False</td>
<td>22.0</td>
<td>361138.0</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">8032</td>
<td>Private</td>
<td>Bachelors</td>
<td>Married-civ-spouse</td>
<td>Sales</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>54.0</td>
<td>391016.0</td>
<td>13.0</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4364</td>
<td>Private</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Craft-repair</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>45.0</td>
<td>380922.0</td>
<td>9.0</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5404</td>
<td>Self-emp-inc</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Farming-fishing</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>60.0</td>
<td>160062.0</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">693</td>
<td>State-gov</td>
<td>Masters</td>
<td>Never-married</td>
<td>Prof-specialty</td>
<td>Not-in-family</td>
<td>Asian-Pac-Islander</td>
<td>True</td>
<td>27.0</td>
<td>315640.0</td>
<td>10.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2684</td>
<td>Self-emp-not-inc</td>
<td>Bachelors</td>
<td>Married-civ-spouse</td>
<td>Farming-fishing</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>84.0</td>
<td>155057.0</td>
<td>13.0</td>
<td>&lt;50k</td>
</tr>
</tbody>
</table>

We can decode any set of transformed data by calling `to.decode_row`
with our raw data:

``` python
row = to.items.iloc[0]
to.decode_row(row)
```

    age                                50.0
    workclass              Self-emp-not-inc
    fnlwgt                         124793.0
    education                       HS-grad
    education-num                       9.0
    marital-status       Married-civ-spouse
    occupation                 Craft-repair
    relationship                    Husband
    race                              White
    sex                                Male
    capital-gain                          0
    capital-loss                          0
    hours-per-week                       30
    native-country            United-States
    salary                             <50k
    education-num_na                  False
    Name: 3564, dtype: object

We can make new test datasets based on the training data with the
`to.new()`

<div>

> **Note**
>
> Since machine learning models can’t magically understand categories it
> was never trained on, the data should reflect this. If there are
> different missing values in your test data you should address this
> before training

</div>

``` python
to_tst = to.new(df_test)
to_tst.process()
to_tst.items.head()
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">age</th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">education-num</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">sex</th>
<th data-quarto-table-cell-role="th">capital-gain</th>
<th data-quarto-table-cell-role="th">capital-loss</th>
<th data-quarto-table-cell-role="th">hours-per-week</th>
<th data-quarto-table-cell-role="th">native-country</th>
<th data-quarto-table-cell-role="th">education-num_na</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">10000</td>
<td>0.470185</td>
<td>5</td>
<td>1.346422</td>
<td>10</td>
<td>1.165893</td>
<td>3</td>
<td>2</td>
<td>1</td>
<td>2</td>
<td>Male</td>
<td>0</td>
<td>0</td>
<td>40</td>
<td>Philippines</td>
<td>1</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">10001</td>
<td>-0.923825</td>
<td>5</td>
<td>1.258980</td>
<td>12</td>
<td>-0.424752</td>
<td>3</td>
<td>15</td>
<td>1</td>
<td>4</td>
<td>Male</td>
<td>0</td>
<td>0</td>
<td>40</td>
<td>United-States</td>
<td>1</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">10002</td>
<td>1.057137</td>
<td>5</td>
<td>0.150986</td>
<td>2</td>
<td>-1.220074</td>
<td>1</td>
<td>9</td>
<td>2</td>
<td>5</td>
<td>Female</td>
<td>0</td>
<td>0</td>
<td>37</td>
<td>United-States</td>
<td>1</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">10003</td>
<td>0.543554</td>
<td>5</td>
<td>-0.284206</td>
<td>12</td>
<td>-0.424752</td>
<td>7</td>
<td>2</td>
<td>5</td>
<td>5</td>
<td>Female</td>
<td>0</td>
<td>0</td>
<td>43</td>
<td>United-States</td>
<td>1</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">10004</td>
<td>0.763661</td>
<td>6</td>
<td>1.449451</td>
<td>9</td>
<td>0.370571</td>
<td>3</td>
<td>5</td>
<td>1</td>
<td>5</td>
<td>Male</td>
<td>0</td>
<td>0</td>
<td>60</td>
<td>United-States</td>
<td>1</td>
</tr>
</tbody>
</table>

</div>

We can then convert it to a
[`DataLoader`](https://docs.fast.ai/data/data.load.html#dataloader):

``` python
tst_dl = dls.valid.new(to_tst)
tst_dl.show_batch()
```

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">education-num_na</th>
<th data-quarto-table-cell-role="th">age</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education-num</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>Private</td>
<td>Bachelors</td>
<td>Married-civ-spouse</td>
<td>Adm-clerical</td>
<td>Husband</td>
<td>Asian-Pac-Islander</td>
<td>False</td>
<td>45.0</td>
<td>338104.995686</td>
<td>13.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>Private</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Transport-moving</td>
<td>Husband</td>
<td>Other</td>
<td>False</td>
<td>26.0</td>
<td>328662.994908</td>
<td>9.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>Private</td>
<td>11th</td>
<td>Divorced</td>
<td>Other-service</td>
<td>Not-in-family</td>
<td>White</td>
<td>False</td>
<td>53.0</td>
<td>209021.999974</td>
<td>7.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>Private</td>
<td>HS-grad</td>
<td>Widowed</td>
<td>Adm-clerical</td>
<td>Unmarried</td>
<td>White</td>
<td>False</td>
<td>46.0</td>
<td>162029.999608</td>
<td>9.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>Self-emp-inc</td>
<td>Assoc-voc</td>
<td>Married-civ-spouse</td>
<td>Exec-managerial</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>49.0</td>
<td>349229.997552</td>
<td>11.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5</td>
<td>Local-gov</td>
<td>Some-college</td>
<td>Married-civ-spouse</td>
<td>Exec-managerial</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>34.0</td>
<td>124826.999041</td>
<td>10.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>Self-emp-inc</td>
<td>Some-college</td>
<td>Married-civ-spouse</td>
<td>Sales</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>53.0</td>
<td>290640.000020</td>
<td>10.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">7</td>
<td>Private</td>
<td>Some-college</td>
<td>Never-married</td>
<td>Sales</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>19.0</td>
<td>106273.001990</td>
<td>10.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">8</td>
<td>Private</td>
<td>Some-college</td>
<td>Married-civ-spouse</td>
<td>Protective-serv</td>
<td>Husband</td>
<td>Black</td>
<td>False</td>
<td>72.0</td>
<td>53684.003204</td>
<td>10.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">9</td>
<td>Private</td>
<td>Some-college</td>
<td>Never-married</td>
<td>Sales</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>20.0</td>
<td>505979.987402</td>
<td>10.0</td>
</tr>
</tbody>
</table>

``` python
# Create a TabWeightedDL
train_ds = to.train
weights = np.random.random(len(train_ds))
train_dl = TabWeightedDL(train_ds, wgts=weights, bs=64, shuffle=True)

train_dl.show_batch()
```

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">education-num_na</th>
<th data-quarto-table-cell-role="th">age</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education-num</th>
<th data-quarto-table-cell-role="th">salary</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>Private</td>
<td>HS-grad</td>
<td>Widowed</td>
<td>Craft-repair</td>
<td>Unmarried</td>
<td>White</td>
<td>False</td>
<td>58.000000</td>
<td>178644.000556</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>Private</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Handlers-cleaners</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>21.000000</td>
<td>131811.002389</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>Private</td>
<td>10th</td>
<td>Never-married</td>
<td>#na#</td>
<td>Own-child</td>
<td>White</td>
<td>True</td>
<td>16.999999</td>
<td>294485.002377</td>
<td>10.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>Private</td>
<td>HS-grad</td>
<td>Widowed</td>
<td>Adm-clerical</td>
<td>Not-in-family</td>
<td>White</td>
<td>False</td>
<td>66.000001</td>
<td>98836.997894</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>Self-emp-not-inc</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Craft-repair</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>28.000000</td>
<td>420054.007486</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5</td>
<td>Federal-gov</td>
<td>Assoc-voc</td>
<td>Divorced</td>
<td>Craft-repair</td>
<td>Not-in-family</td>
<td>White</td>
<td>False</td>
<td>43.000000</td>
<td>92774.997808</td>
<td>11.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>?</td>
<td>Some-college</td>
<td>Never-married</td>
<td>?</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>19.000000</td>
<td>234518.999208</td>
<td>10.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">7</td>
<td>Private</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Craft-repair</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>35.000000</td>
<td>186009.000006</td>
<td>9.0</td>
<td>&gt;=50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">8</td>
<td>Federal-gov</td>
<td>HS-grad</td>
<td>Never-married</td>
<td>Adm-clerical</td>
<td>Own-child</td>
<td>Black</td>
<td>False</td>
<td>25.000000</td>
<td>144258.998968</td>
<td>9.0</td>
<td>&lt;50k</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">9</td>
<td>?</td>
<td>Some-college</td>
<td>Never-married</td>
<td>?</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>20.000000</td>
<td>117788.996828</td>
<td>10.0</td>
<td>&lt;50k</td>
</tr>
</tbody>
</table>

TabDataLoader’s create_item method

``` python
df = pd.DataFrame([{'age': 35}])
to = TabularPandas(df)
dls = to.dataloaders()
print(dls.create_item(0))
# test_eq(dls.create_item(0).items.to_dict(), {'age': 0.5330614747286777, 'workclass': 5, 'fnlwgt': -0.26305443080666174, 'education': 10, 'education-num': 1.169790230219763, 'marital-status': 1, 'occupation': 13, 'relationship': 5, 'race': 3, 'sex': ' Female', 'capital-gain': 0, 'capital-loss': 0, 'hours-per-week': 35, 'native-country': 'United-States', 'salary': 1, 'education-num_na': 1})
```

    age    35
    Name: 0, dtype: int8

## Other target types

### Multi-label categories

#### one-hot encoded label

``` python
def _mock_multi_label(df):
    sal,sex,white = [],[],[]
    for row in df.itertuples():
        sal.append(row.salary == '>=50k')
        sex.append(row.sex == ' Male')
        white.append(row.race == ' White')
    df['salary'] = np.array(sal)
    df['male']   = np.array(sex)
    df['white']  = np.array(white)
    return df
```

``` python
path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv')
df_main,df_test = df.iloc[:10000].copy(),df.iloc[10000:].copy()
df_main = _mock_multi_label(df_main)
```

``` python
df_main.head()
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">age</th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">education-num</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">sex</th>
<th data-quarto-table-cell-role="th">capital-gain</th>
<th data-quarto-table-cell-role="th">capital-loss</th>
<th data-quarto-table-cell-role="th">hours-per-week</th>
<th data-quarto-table-cell-role="th">native-country</th>
<th data-quarto-table-cell-role="th">salary</th>
<th data-quarto-table-cell-role="th">male</th>
<th data-quarto-table-cell-role="th">white</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>49</td>
<td>Private</td>
<td>101320</td>
<td>Assoc-acdm</td>
<td>12.0</td>
<td>Married-civ-spouse</td>
<td>NaN</td>
<td>Wife</td>
<td>White</td>
<td>Female</td>
<td>0</td>
<td>1902</td>
<td>40</td>
<td>United-States</td>
<td>True</td>
<td>False</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>44</td>
<td>Private</td>
<td>236746</td>
<td>Masters</td>
<td>14.0</td>
<td>Divorced</td>
<td>Exec-managerial</td>
<td>Not-in-family</td>
<td>White</td>
<td>Male</td>
<td>10520</td>
<td>0</td>
<td>45</td>
<td>United-States</td>
<td>True</td>
<td>True</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>38</td>
<td>Private</td>
<td>96185</td>
<td>HS-grad</td>
<td>NaN</td>
<td>Divorced</td>
<td>NaN</td>
<td>Unmarried</td>
<td>Black</td>
<td>Female</td>
<td>0</td>
<td>0</td>
<td>32</td>
<td>United-States</td>
<td>False</td>
<td>False</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>38</td>
<td>Self-emp-inc</td>
<td>112847</td>
<td>Prof-school</td>
<td>15.0</td>
<td>Married-civ-spouse</td>
<td>Prof-specialty</td>
<td>Husband</td>
<td>Asian-Pac-Islander</td>
<td>Male</td>
<td>0</td>
<td>0</td>
<td>40</td>
<td>United-States</td>
<td>True</td>
<td>True</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>42</td>
<td>Self-emp-not-inc</td>
<td>82297</td>
<td>7th-8th</td>
<td>NaN</td>
<td>Married-civ-spouse</td>
<td>Other-service</td>
<td>Wife</td>
<td>Black</td>
<td>Female</td>
<td>0</td>
<td>0</td>
<td>50</td>
<td>United-States</td>
<td>False</td>
<td>False</td>
<td>False</td>
</tr>
</tbody>
</table>

</div>

``` python
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']
cont_names = ['age', 'fnlwgt', 'education-num']
procs = [Categorify, FillMissing, Normalize]
splits = RandomSplitter()(range_of(df_main))
y_names=["salary", "male", "white"]
```

``` python
%time to = TabularPandas(df_main, procs, cat_names, cont_names, y_names=y_names, y_block=MultiCategoryBlock(encoded=True, vocab=y_names), splits=splits)
```

    CPU times: user 30.8 ms, sys: 774 us, total: 31.6 ms
    Wall time: 31.4 ms

``` python
dls = to.dataloaders()
dls.valid.show_batch()
```

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">education-num_na</th>
<th data-quarto-table-cell-role="th">age</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education-num</th>
<th data-quarto-table-cell-role="th">salary</th>
<th data-quarto-table-cell-role="th">male</th>
<th data-quarto-table-cell-role="th">white</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>Private</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Machine-op-inspct</td>
<td>Wife</td>
<td>Black</td>
<td>False</td>
<td>35.000000</td>
<td>110668.001907</td>
<td>9.0</td>
<td>False</td>
<td>False</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>Private</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Craft-repair</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>51.000000</td>
<td>33303.995791</td>
<td>9.0</td>
<td>False</td>
<td>True</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>Private</td>
<td>Some-college</td>
<td>Never-married</td>
<td>Adm-clerical</td>
<td>Not-in-family</td>
<td>White</td>
<td>False</td>
<td>37.000000</td>
<td>38468.006454</td>
<td>10.0</td>
<td>False</td>
<td>False</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>?</td>
<td>Some-college</td>
<td>Married-civ-spouse</td>
<td>?</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>63.999999</td>
<td>108082.000741</td>
<td>10.0</td>
<td>False</td>
<td>True</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>Private</td>
<td>Bachelors</td>
<td>Married-civ-spouse</td>
<td>Prof-specialty</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>38.000000</td>
<td>187747.999948</td>
<td>13.0</td>
<td>True</td>
<td>True</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5</td>
<td>Private</td>
<td>HS-grad</td>
<td>Never-married</td>
<td>Tech-support</td>
<td>Not-in-family</td>
<td>Asian-Pac-Islander</td>
<td>False</td>
<td>28.000000</td>
<td>375313.002386</td>
<td>9.0</td>
<td>False</td>
<td>True</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>Private</td>
<td>HS-grad</td>
<td>Divorced</td>
<td>#na#</td>
<td>Unmarried</td>
<td>White</td>
<td>True</td>
<td>36.000000</td>
<td>130199.998135</td>
<td>10.0</td>
<td>False</td>
<td>True</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">7</td>
<td>Private</td>
<td>11th</td>
<td>Married-civ-spouse</td>
<td>Craft-repair</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>36.000000</td>
<td>123151.001427</td>
<td>7.0</td>
<td>False</td>
<td>True</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">8</td>
<td>Private</td>
<td>Bachelors</td>
<td>Never-married</td>
<td>Adm-clerical</td>
<td>Not-in-family</td>
<td>Asian-Pac-Islander</td>
<td>False</td>
<td>32.000000</td>
<td>107218.002435</td>
<td>13.0</td>
<td>False</td>
<td>True</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">9</td>
<td>Private</td>
<td>11th</td>
<td>Divorced</td>
<td>Other-service</td>
<td>Unmarried</td>
<td>White</td>
<td>False</td>
<td>32.000000</td>
<td>185732.000241</td>
<td>7.0</td>
<td>False</td>
<td>False</td>
<td>True</td>
</tr>
</tbody>
</table>

#### Not one-hot encoded

``` python
def _mock_multi_label(df):
    targ = []
    for row in df.itertuples():
        labels = []
        if row.salary == '>=50k': labels.append('>50k')
        if row.sex == ' Male':   labels.append('male')
        if row.race == ' White': labels.append('white')
        targ.append(' '.join(labels))
    df['target'] = np.array(targ)
    return df
```

``` python
path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv')
df_main,df_test = df.iloc[:10000].copy(),df.iloc[10000:].copy()
df_main = _mock_multi_label(df_main)
```

``` python
df_main.head()
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">age</th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">education-num</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">sex</th>
<th data-quarto-table-cell-role="th">capital-gain</th>
<th data-quarto-table-cell-role="th">capital-loss</th>
<th data-quarto-table-cell-role="th">hours-per-week</th>
<th data-quarto-table-cell-role="th">native-country</th>
<th data-quarto-table-cell-role="th">salary</th>
<th data-quarto-table-cell-role="th">target</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>49</td>
<td>Private</td>
<td>101320</td>
<td>Assoc-acdm</td>
<td>12.0</td>
<td>Married-civ-spouse</td>
<td>NaN</td>
<td>Wife</td>
<td>White</td>
<td>Female</td>
<td>0</td>
<td>1902</td>
<td>40</td>
<td>United-States</td>
<td>&gt;=50k</td>
<td>&gt;50k white</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>44</td>
<td>Private</td>
<td>236746</td>
<td>Masters</td>
<td>14.0</td>
<td>Divorced</td>
<td>Exec-managerial</td>
<td>Not-in-family</td>
<td>White</td>
<td>Male</td>
<td>10520</td>
<td>0</td>
<td>45</td>
<td>United-States</td>
<td>&gt;=50k</td>
<td>&gt;50k male white</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>38</td>
<td>Private</td>
<td>96185</td>
<td>HS-grad</td>
<td>NaN</td>
<td>Divorced</td>
<td>NaN</td>
<td>Unmarried</td>
<td>Black</td>
<td>Female</td>
<td>0</td>
<td>0</td>
<td>32</td>
<td>United-States</td>
<td>&lt;50k</td>
<td></td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>38</td>
<td>Self-emp-inc</td>
<td>112847</td>
<td>Prof-school</td>
<td>15.0</td>
<td>Married-civ-spouse</td>
<td>Prof-specialty</td>
<td>Husband</td>
<td>Asian-Pac-Islander</td>
<td>Male</td>
<td>0</td>
<td>0</td>
<td>40</td>
<td>United-States</td>
<td>&gt;=50k</td>
<td>&gt;50k male</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>42</td>
<td>Self-emp-not-inc</td>
<td>82297</td>
<td>7th-8th</td>
<td>NaN</td>
<td>Married-civ-spouse</td>
<td>Other-service</td>
<td>Wife</td>
<td>Black</td>
<td>Female</td>
<td>0</td>
<td>0</td>
<td>50</td>
<td>United-States</td>
<td>&lt;50k</td>
<td></td>
</tr>
</tbody>
</table>

</div>

``` python
@MultiCategorize
def encodes(self, to:Tabular):
    #to.transform(to.y_names, partial(_apply_cats, {n: self.vocab for n in to.y_names}, 0))
    return to

@MultiCategorize
def decodes(self, to:Tabular):
    #to.transform(to.y_names, partial(_decode_cats, {n: self.vocab for n in to.y_names}))
    return to
```

``` python
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']
cont_names = ['age', 'fnlwgt', 'education-num']
procs = [Categorify, FillMissing, Normalize]
splits = RandomSplitter()(range_of(df_main))
```

``` python
%time to = TabularPandas(df_main, procs, cat_names, cont_names, y_names="target", y_block=MultiCategoryBlock(), splits=splits)
```

    CPU times: user 10.5 ms, sys: 201 us, total: 10.7 ms
    Wall time: 10.6 ms

``` python
to.procs[2].vocab
```

    ['-', '_', 'a', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y']

### Regression

``` python
path = untar_data(URLs.ADULT_SAMPLE)
df = pd.read_csv(path/'adult.csv')
df_main,df_test = df.iloc[:10000].copy(),df.iloc[10000:].copy()
df_main = _mock_multi_label(df_main)
```

``` python
cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']
cont_names = ['fnlwgt', 'education-num']
procs = [Categorify, FillMissing, Normalize]
splits = RandomSplitter()(range_of(df_main))
```

``` python
%time to = TabularPandas(df_main, procs, cat_names, cont_names, y_names='age', splits=splits)
```

    CPU times: user 21.8 ms, sys: 969 us, total: 22.7 ms
    Wall time: 21.9 ms

``` python
to.procs[-1].means
```

    {'fnlwgt': np.float64(192511.077125),
     'education-num': np.float64(10.076749801635742)}

``` python
dls = to.dataloaders()
dls.valid.show_batch()
```

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">workclass</th>
<th data-quarto-table-cell-role="th">education</th>
<th data-quarto-table-cell-role="th">marital-status</th>
<th data-quarto-table-cell-role="th">occupation</th>
<th data-quarto-table-cell-role="th">relationship</th>
<th data-quarto-table-cell-role="th">race</th>
<th data-quarto-table-cell-role="th">education-num_na</th>
<th data-quarto-table-cell-role="th">fnlwgt</th>
<th data-quarto-table-cell-role="th">education-num</th>
<th data-quarto-table-cell-role="th">age</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>Local-gov</td>
<td>Some-college</td>
<td>Married-spouse-absent</td>
<td>Exec-managerial</td>
<td>Unmarried</td>
<td>Black</td>
<td>False</td>
<td>216129.000726</td>
<td>10.0</td>
<td>38.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>Private</td>
<td>HS-grad</td>
<td>Divorced</td>
<td>Protective-serv</td>
<td>Not-in-family</td>
<td>Black</td>
<td>False</td>
<td>162814.000297</td>
<td>9.0</td>
<td>34.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>Private</td>
<td>Bachelors</td>
<td>Married-civ-spouse</td>
<td>Exec-managerial</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>193881.999975</td>
<td>13.0</td>
<td>44.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>Local-gov</td>
<td>HS-grad</td>
<td>Married-civ-spouse</td>
<td>Exec-managerial</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>144778.000789</td>
<td>9.0</td>
<td>43.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>Private</td>
<td>HS-grad</td>
<td>Never-married</td>
<td>Other-service</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>304385.993937</td>
<td>9.0</td>
<td>24.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5</td>
<td>Private</td>
<td>5th-6th</td>
<td>Never-married</td>
<td>Craft-repair</td>
<td>Not-in-family</td>
<td>White</td>
<td>False</td>
<td>155621.001484</td>
<td>3.0</td>
<td>28.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>Self-emp-not-inc</td>
<td>7th-8th</td>
<td>Divorced</td>
<td>Other-service</td>
<td>Unmarried</td>
<td>White</td>
<td>False</td>
<td>385632.000374</td>
<td>4.0</td>
<td>56.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">7</td>
<td>Private</td>
<td>Bachelors</td>
<td>Never-married</td>
<td>Prof-specialty</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>244365.998597</td>
<td>13.0</td>
<td>22.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">8</td>
<td>Private</td>
<td>11th</td>
<td>Divorced</td>
<td>Handlers-cleaners</td>
<td>Own-child</td>
<td>White</td>
<td>False</td>
<td>112262.998271</td>
<td>7.0</td>
<td>30.0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">9</td>
<td>Local-gov</td>
<td>Some-college</td>
<td>Married-civ-spouse</td>
<td>Protective-serv</td>
<td>Husband</td>
<td>White</td>
<td>False</td>
<td>195258.000082</td>
<td>10.0</td>
<td>41.0</td>
</tr>
</tbody>
</table>

## Not being used now - for multi-modal

``` python
class TensorTabular(fastuple):
    def get_ctxs(self, max_n=10, **kwargs):
        n_samples = min(self[0].shape[0], max_n)
        df = pd.DataFrame(index = range(n_samples))
        return [df.iloc[i] for i in range(n_samples)]

    def display(self, ctxs): display_df(pd.DataFrame(ctxs))

class TabularLine(pd.Series):
    "A line of a dataframe that knows how to show itself"
    def show(self, ctx=None, **kwargs): return self if ctx is None else ctx.append(self)

class ReadTabLine(ItemTransform):
    def __init__(self, proc): self.proc = proc

    def encodes(self, row):
        cats,conts = (o.map(row.__getitem__) for o in (self.proc.cat_names,self.proc.cont_names))
        return TensorTabular(tensor(cats).long(),tensor(conts).float())

    def decodes(self, o):
        to = TabularPandas(o, self.proc.cat_names, self.proc.cont_names, self.proc.y_names)
        to = self.proc.decode(to)
        return TabularLine(pd.Series({c: v for v,c in zip(to.items[0]+to.items[1], self.proc.cat_names+self.proc.cont_names)}))

class ReadTabTarget(ItemTransform):
    def __init__(self, proc): self.proc = proc
    def encodes(self, row): return row[self.proc.y_names].astype(np.int64)
    def decodes(self, o): return Category(self.proc.classes[self.proc.y_names][o])
```

``` python
# tds = TfmdDS(to.items, tfms=[[ReadTabLine(proc)], ReadTabTarget(proc)])
# enc = tds[1]
# test_eq(enc[0][0], tensor([2,1]))
# test_close(enc[0][1], tensor([-0.628828]))
# test_eq(enc[1], 1)

# dec = tds.decode(enc)
# assert isinstance(dec[0], TabularLine)
# test_close(dec[0], pd.Series({'a': 1, 'b_na': False, 'b': 1}))
# test_eq(dec[1], 'a')

# test_stdout(lambda: print(show_at(tds, 1)), """a               1
# b_na        False
# b               1
# category        a
# dtype: object""")
```
