# Preprocessing with the Apache Beam DataFrames API

<br />

[Pandas DataFrames](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) is one of the most common tools used for data exploration and preprocessing. Pandas is popular because of its ease of use. It has intuitive methods to perform common analytical tasks and data preprocessing.

|---|---|
| [Run in Google Colab](https://colab.research.google.com/github/apache/beam/blob/master/examples/notebooks/beam-ml/dataframe_api_preprocessing.ipynb) | [View source on GitHub](https://github.com/apache/beam/blob/master/examples/notebooks/beam-ml/dataframe_api_preprocessing.ipynb) |

For rapid execution, Pandas loads all of the data into memory on a single machine (one node). This configuration works well when dealing with small-scale datasets. However, many projects involve datasets that are too big to fit in memory. These use cases generally require parallel data processing frameworks, such as Apache Beam.

Beam DataFrames provide a Pandas-like
API to declare and define Beam processing pipelines. It provides a familiar interface for machine learning practioners to build complex data-processing pipelines by only invoking standard pandas commands.

To learn more about Apache Beam DataFrames, see the
[Beam DataFrames overview](https://beam.apache.org/documentation/dsls/dataframes/overview) page.

## Overview

The goal of this example is to explore a dataset preprocessed with the Beam DataFrame API for machine learning model training.

This example demonstrates the use of the Apache Beam DataFrames API to perform common data exploration as well as the preprocessing steps that are necessary to prepare your dataset for machine learning model training and inference. This example includes the following steps:

- Removing unwanted columns.
- One-hot encoding categorical columns.
- Normalizing numerical columns.

In this example, the first section demonstrates how to build and execute a pipeline locally using the interactive runner.
The second section uses a distributed runner to demonstrate how to run the pipeline on the full dataset.

## Install Apache Beam

To explore the elements within a `PCollection`, install Apache Beam with the `interactive` component to use the Interactive runner. The DataFrames API methods invoked in this example are available in Apache Beam SDK versions 2.43 and later.

Install the latest Apache Beam SDK version.

    !git clone https://github.com/apache/beam.git

    !cd beam/sdks/python && pip3 install -r build-requirements.txt 

    %pip install -e beam/sdks/python/.[interactive,gcp]

## Local exploration with the Interactive Beam runner

Use the [Interactive Beam](https://beam.apache.org/releases/pydoc/2.20.0/apache_beam.runners.interactive.interactive_beam.html) runner to explore and develop your pipeline.
This runner allows you to test the code interactively, progressively building out the pipeline before deploying it on a distributed runner.

This section uses a subset of the original dataset, because the notebook instance has limited compute resources.

### Load the data

To read CSV files into DataFrames, Pandas has the
[`pandas.read_csv`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html)
function.
This notebook uses the Beam
[`beam.dataframe.io.read_csv`](https://beam.apache.org/releases/pydoc/current/apache_beam.dataframe.io.html#apache_beam.dataframe.io.read_csv)
function, which emulates `pandas.read_csv`. The main difference is that the Beam function returns a deferred Beam DataFrame, whereas the Pandas function returns a standard DataFrame.

    import os

    import numpy as np
    import pandas as pd 
    import apache_beam as beam
    import apache_beam.runners.interactive.interactive_beam as ib
    from apache_beam import dataframe
    from apache_beam.runners.interactive.interactive_runner import InteractiveRunner
    from apache_beam.runners.dataflow import DataflowRunner

    # Available options: [sample_1000, sample_10000, sample_100000, full], where
    # sample contains the entire dataset (around 1000000 samples).

    source_csv_file = 'gs://apache-beam-samples/nasa_jpl_asteroid/sample_10000.csv'

    # Initialize the pipeline.
    p = beam.Pipeline(InteractiveRunner())

    beam_df = p | beam.dataframe.io.read_csv(source_csv_file)

### Preprocess the data

This example uses the [NASA - Nearest Earth Objects dataset](https://cneos.jpl.nasa.gov/ca/).
This dataset includes information about objects in outer space. Some objects are close enough to Earth to cause harm.
This dataset compiles the list of NASA certified asteroids that are classified as the nearest earth objects to understand which objects pose a risk.

Inspect the dataset columns and their types.

    beam_df.dtypes

```
spk_id                       int64
full_name                   object
near_earth_object           object
absolute_magnitude         float64
diameter                   float64
albedo                     float64
diameter_sigma             float64
eccentricity               float64
inclination                float64
moid_ld                    float64
object_class                object
semi_major_axis_au_unit    float64
hazardous_flag              object
dtype: object
```

When using Interactive Beam, to bring a Beam DataFrame into local memory as a Pandas DataFrame, use `ib.collect()`.

    ib.collect(beam_df)

|   | spk_id | full_name | near_earth_object | absolute_magnitude | diameter | albedo | diameter_sigma | eccentricity | inclination | moid_ld | object_class | semi_major_axis_au_unit | hazardous_flag |
| 0 | 2000001 | 1 Ceres | N | 3.40 | 939.400 | 0.0900 | 0.200 | 0.076009 | 10.594067 | 620.640533 | MBA | 2.769165 | N |
| 1 | 2000002 | 2 Pallas | N | 4.20 | 545.000 | 0.1010 | 18.000 | 0.229972 | 34.832932 | 480.348639 | MBA | 2.773841 | N |
| 2 | 2000003 | 3 Juno | N | 5.33 | 246.596 | 0.2140 | 10.594 | 0.256936 | 12.991043 | 402.514639 | MBA | 2.668285 | N |
| 3 | 2000004 | 4 Vesta | N | 3.00 | 525.400 | 0.4228 | 0.200 | 0.088721 | 7.141771 | 443.451432 | MBA | 2.361418 | N |
| 4 | 2000005 | 5 Astraea | N | 6.90 | 106.699 | 0.2740 | 3.140 | 0.190913 | 5.367427 | 426.433027 | MBA | 2.574037 | N |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 9994 | 2009995 | 9995 Alouette (4805 P-L) | N | 15.10 | 2.564 | 0.2450 | 0.550 | 0.160610 | 2.311731 | 388.723233 | MBA | 2.390249 | N |
| 9995 | 2009996 | 9996 ANS (9070 P-L) | N | 13.60 | 8.978 | 0.1130 | 0.376 | 0.235174 | 7.657713 | 444.194746 | MBA | 2.796605 | N |
| 9996 | 2009997 | 9997 COBE (1217 T-1) | N | 14.30 | NaN | NaN | NaN | 0.113059 | 2.459643 | 495.460110 | MBA | 2.545674 | N |
| 9997 | 2009998 | 9998 ISO (1293 T-1) | N | 15.10 | 2.235 | 0.3880 | 0.373 | 0.093852 | 3.912263 | 373.848377 | MBA | 2.160961 | N |
| 9998 | 2009999 | 9999 Wiles (4196 T-2) | N | 13.00 | 7.148 | 0.2620 | 0.065 | 0.071351 | 3.198839 | 632.144398 | MBA | 2.839917 | N |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|

9999 rows × 13 columns
<button class="colab-df-convert" title="Convert this dataframe to an interactive table." style="display:none;"> </button>

The datasets contain the following two types of columns:

- **Numerical columns:** Use [normalization](https://developers.google.com/machine-learning/data-prep/transform/normalization) to transform these columns so that they can be used to train a machine learning model.

- **Categorical columns:** Transform those columns with [one-hot encoding](https://developers.google.com/machine-learning/data-prep/transform/transform-categorical) to use them during training.

Use the standard pandas command `DataFrame.describe()` to generate descriptive statistics for the numerical columns, such as percentile, mean, std, and so on.

    with dataframe.allow_non_parallel_operations():
      beam_df_description = ib.collect(beam_df.describe())

    beam_df_description

|   | spk_id | absolute_magnitude | diameter | albedo | diameter_sigma | eccentricity | inclination | moid_ld | semi_major_axis_au_unit |
| count | 9.999000e+03 | 9999.000000 | 8688.000000 | 8672.000000 | 8591.000000 | 9999.000000 | 9999.000000 | 9999.000000 | 9999.000000 |
| mean | 2.005000e+06 | 12.675380 | 19.245446 | 0.197723 | 0.454072 | 0.148716 | 7.890742 | 509.805237 | 2.689836 |
| std | 2.886607e+03 | 1.639609 | 30.190191 | 0.138819 | 1.093676 | 0.083803 | 6.336244 | 205.046582 | 0.607190 |
| min | 2.000001e+06 | 3.000000 | 0.300000 | 0.008000 | 0.006000 | 0.001003 | 0.042716 | 0.131028 | 0.832048 |
| 25% | 2.002500e+06 | 11.900000 | 5.614000 | 0.074000 | 0.120000 | 0.093780 | 3.220137 | 377.829197 | 2.340816 |
| 50% | 2.005000e+06 | 12.900000 | 9.814000 | 0.187000 | 0.201000 | 0.140335 | 6.018836 | 470.650523 | 2.614468 |
| 75% | 2.007500e+06 | 13.700000 | 19.156750 | 0.283000 | 0.375000 | 0.187092 | 10.918176 | 636.010802 | 3.005449 |
| max | 2.009999e+06 | 20.700000 | 939.400000 | 1.000000 | 39.297000 | 0.889831 | 68.018875 | 4241.524913 | 24.667968 |
|---|---|---|---|---|---|---|---|---|---|

<button class="colab-df-convert" title="Convert this dataframe to an interactive table." style="display:none;"> </button>

Before running any transformations, verify that all of the columns need to be used for model training. Start by looking at the column description provided by the [JPL website](https://ssd.jpl.nasa.gov/sbdb_query.cgi):

- **spk_id:** Object primary SPK-ID.
- **full_name:** Asteroid name.
- **near_earth_object:** Near-earth object flag.
- **absolute_magnitude:** The apparent magnitude an object would have if it were located at a distance of 10 parsecs.
- **diameter:** Object diameter (from equivalent sphere) km unit.
- **albedo:** A measure of the diffuse reflection of solar radiation out of the total solar radiation, measured on a scale from 0 to 1.
- **diameter_sigma:** 1-sigma uncertainty in object diameter km unit.
- **eccentricity:** A value between 0 and 1 that refers to how flat or round the asteroid is.
- **inclination:** The angle with respect to the x-y ecliptic plane.
- **moid_ld:** Earth Minimum Orbit Intersection Distance au unit.
- **object_class:** The classification of the asteroid. For a more detailed description, see [NASA object classifications](https://pdssbn.astro.umd.edu/data_other/objclass.shtml).
- **Semi-major axis au Unit:** The length of half of the long axis in AU unit.
- **hazardous_flag:** Identifies hazardous asteroids.

The **spk_id** and **full_name** columns are unique for each row. You can remove these columns, because they are not needed for model training.

    beam_df = beam_df.drop(['spk_id', 'full_name'], axis='columns', inplace=False)

Review the number of missing values.

    ib.collect(beam_df.isnull().mean() * 100)

```
/content/beam/sdks/python/apache_beam/dataframe/frame_base.py:145: RuntimeWarning: invalid value encountered in long_scalars
  lambda left, right: getattr(left, op)(right), name=op, args=[other])
near_earth_object           0.000000
absolute_magnitude          0.000000
diameter                   13.111311
albedo                     13.271327
diameter_sigma             14.081408
eccentricity                0.000000
inclination                 0.000000
moid_ld                     0.000000
object_class                0.000000
semi_major_axis_au_unit     0.000000
hazardous_flag              0.000000
dtype: float64
```

Most of the columns do not have missing values. However, the columns **diameter** , **albedo** , and **diameter_sigma** have many missing values. Because these values cannot be measured or derived and aren't needed for training the ML model, remove the columns.

    beam_df = beam_df.drop(['diameter', 'albedo', 'diameter_sigma'], axis='columns', inplace=False)
    ib.collect(beam_df)

|   | near_earth_object | absolute_magnitude | eccentricity | inclination | moid_ld | object_class | semi_major_axis_au_unit | hazardous_flag |
| 0 | N | 3.40 | 0.076009 | 10.594067 | 620.640533 | MBA | 2.769165 | N |
| 1 | N | 4.20 | 0.229972 | 34.832932 | 480.348639 | MBA | 2.773841 | N |
| 2 | N | 5.33 | 0.256936 | 12.991043 | 402.514639 | MBA | 2.668285 | N |
| 3 | N | 3.00 | 0.088721 | 7.141771 | 443.451432 | MBA | 2.361418 | N |
| 4 | N | 6.90 | 0.190913 | 5.367427 | 426.433027 | MBA | 2.574037 | N |
| ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 9994 | N | 15.10 | 0.160610 | 2.311731 | 388.723233 | MBA | 2.390249 | N |
| 9995 | N | 13.60 | 0.235174 | 7.657713 | 444.194746 | MBA | 2.796605 | N |
| 9996 | N | 14.30 | 0.113059 | 2.459643 | 495.460110 | MBA | 2.545674 | N |
| 9997 | N | 15.10 | 0.093852 | 3.912263 | 373.848377 | MBA | 2.160961 | N |
| 9998 | N | 13.00 | 0.071351 | 3.198839 | 632.144398 | MBA | 2.839917 | N |
|---|---|---|---|---|---|---|---|---|

9999 rows × 8 columns
<button class="colab-df-convert" title="Convert this dataframe to an interactive table." style="display:none;"> </button>

### Normalize the data

Normalize the numerical columns so that they can be used to train a model. To standarize the data, you can subtract the mean and divide by the standard deviation. This process is also known as finding the [z-score](https://developers.google.com/machine-learning/data-prep/transform/normalization#z-score).
This step improves the performance and training stability of the model during training and inference.

First, retrieve both the numerical columns and the categorical columns.

    numerical_cols = beam_df.select_dtypes(include=np.number).columns.tolist()
    categorical_cols = list(set(beam_df.columns) - set(numerical_cols))

    # Get the numerical columns.
    beam_df_numericals = beam_df.filter(items=numerical_cols)

    # Standarize DataFrames with only the numerical columns.
    beam_df_numericals = (beam_df_numericals - beam_df_numericals.mean())/beam_df_numericals.std()

    ib.collect(beam_df_numericals)

```
/content/beam/sdks/python/apache_beam/dataframe/frame_base.py:145: RuntimeWarning: invalid value encountered in double_scalars
  lambda left, right: getattr(left, op)(right), name=op, args=[other])
```

|   | absolute_magnitude | eccentricity | inclination | moid_ld | semi_major_axis_au_unit |
| 306 | -1.570727 | -0.062543 | -0.278518 | 0.373194 | 0.357201 |
| 310 | -1.631718 | -1.724526 | -0.736389 | 1.087833 | 0.344233 |
| 546 | -1.753698 | 1.028793 | 1.415303 | -0.339489 | 0.139080 |
| 635 | -1.875678 | 0.244869 | 0.005905 | 0.214107 | 0.367559 |
| 701 | -3.278451 | -1.570523 | 2.006145 | 1.542754 | 0.829337 |
| ... | ... | ... | ... | ... | ... |
| 9697 | 0.807888 | -1.151809 | -0.082944 | -0.129556 | -0.533538 |
| 9813 | 1.722740 | 0.844551 | -0.583247 | -1.006447 | -0.677961 |
| 9868 | 0.807888 | -0.207399 | -0.784665 | -0.462136 | -0.539794 |
| 9903 | 0.868878 | 0.460086 | 0.092258 | -0.107597 | 0.071794 |
| 9956 | 0.746898 | -0.234132 | -0.161116 | -0.601379 | -0.664887 |
|---|---|---|---|---|---|

9999 rows × 5 columns
<button class="colab-df-convert" title="Convert this dataframe to an interactive table." style="display:none;"> </button>

Next, convert the categorical columns into one-hot encoded variables to use during training.

    def get_one_hot_encoding(df: pd.DataFrame, categorical_col:list) -> pd.DataFrame:
      beam_df_categorical= beam_df[categorical_col]
      # Get unique values.
      with dataframe.allow_non_parallel_operations():
        unique_classes = pd.CategoricalDtype(ib.collect(beam_df_categorical.unique(as_series=True)))
      # Use `str.get_dummies()` to get the one-hot encoded representation of the categorical columns.
      beam_df_categorical = beam_df_categorical.astype(unique_classes).str.get_dummies()
      # Add a column name prefix to the newly created categorical columns.
      beam_df_categorical = beam_df_categorical.add_prefix(f'{categorical_col}_')

      return beam_df_categorical

    for categorical_col in categorical_cols:
      beam_df_categorical = get_one_hot_encoding(df=beam_df, categorical_col=categorical_col)
      beam_df_numericals = beam_df_numericals.merge(beam_df_categorical, left_index = True, right_index = True)
    ib.collect(beam_df_numericals)

|   | absolute_magnitude | eccentricity | inclination | moid_ld | semi_major_axis_au_unit | near_earth_object_N | near_earth_object_Y | near_earth_object_nan | object_class_AMO | object_class_APO | ... | object_class_CEN | object_class_IMB | object_class_MBA | object_class_MCA | object_class_OMB | object_class_TJN | object_class_nan | hazardous_flag_N | hazardous_flag_Y | hazardous_flag_nan |
| 0 | -5.657067 | -0.867596 | 0.426645 | 0.540537 | 0.130649 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 12 | -3.583402 | -0.756931 | 1.364340 | 0.238610 | -0.187375 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 47 | -3.400432 | -0.912290 | -0.211925 | 1.136060 | 0.691182 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 381 | -2.363599 | 0.271412 | -0.078826 | 0.535299 | 0.712755 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 515 | -2.729540 | 1.469775 | 0.799915 | -0.602881 | -0.014654 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 9146 | 0.563927 | -0.508757 | -0.327512 | -0.637391 | -0.820638 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 9657 | 1.478779 | 0.487849 | -0.637779 | -0.648240 | -0.468778 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 9704 | 0.380957 | -0.238383 | 0.443053 | 0.670490 | 0.587128 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 9879 | 1.295809 | -0.442966 | -0.698505 | -0.494818 | -0.662602 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 9980 | 0.746898 | -1.455992 | -0.849144 | 0.592902 | -0.022726 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|

9999 rows × 22 columns
<button class="colab-df-convert" title="Convert this dataframe to an interactive table." style="display:none;"> </button>

### Run the pipeline

This section combines the previous steps into a full pipeline implementation, and then visualizes the preprocessed data.

Note that the only standard Apache Beam method invoked here is the `pipeline` instance. The rest of the preprocessing commands are based on native pandas methods that are integrated with the Apache Beam DataFrame API.

    # Specify the location of the source CSV file.
    source_csv_file = 'gs://apache-beam-samples/nasa_jpl_asteroid/sample_10000.csv'

    # Initialize the pipeline.
    p = beam.Pipeline(InteractiveRunner())

    # Create a deferred Apache Beam DataFrame with the contents of the CSV file.
    beam_df = p | beam.dataframe.io.read_csv(source_csv_file)

    # Drop irrelevant columns and columns with missing values.
    beam_df = beam_df.drop(['spk_id', 'full_name','diameter', 'albedo', 'diameter_sigma'], axis='columns', inplace=False)

    # Get numerical columns and columns with categorical values.
    numerical_cols = beam_df.select_dtypes(include=np.number).columns.tolist()
    categorical_cols = list(set(beam_df.columns) - set(numerical_cols))

    # Normalize the numerical values.
    beam_df_numericals = beam_df.filter(items=numerical_cols)
    beam_df_numericals = (beam_df_numericals - beam_df_numericals.mean())/beam_df_numericals.std()


    # One-hot encode the categorical values.
    for categorical_col in categorical_cols:
      beam_df_categorical= get_one_hot_encoding(df=beam_df, categorical_col=categorical_col)
      beam_df_numericals = beam_df_numericals.merge(beam_df_categorical, left_index = True, right_index = True)

    ib.collect(beam_df_numericals)

```
/content/beam/sdks/python/apache_beam/dataframe/frame_base.py:145: RuntimeWarning: invalid value encountered in double_scalars
  lambda left, right: getattr(left, op)(right), name=op, args=[other])
```

|   | absolute_magnitude | eccentricity | inclination | moid_ld | semi_major_axis_au_unit | near_earth_object_N | near_earth_object_Y | near_earth_object_nan | object_class_AMO | object_class_APO | ... | object_class_CEN | object_class_IMB | object_class_MBA | object_class_MCA | object_class_OMB | object_class_TJN | object_class_nan | hazardous_flag_N | hazardous_flag_Y | hazardous_flag_nan |
| 0 | -5.657067 | -0.867596 | 0.426645 | 0.540537 | 0.130649 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 12 | -3.583402 | -0.756931 | 1.364340 | 0.238610 | -0.187375 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 47 | -3.400432 | -0.912290 | -0.211925 | 1.136060 | 0.691182 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 381 | -2.363599 | 0.271412 | -0.078826 | 0.535299 | 0.712755 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 515 | -2.729540 | 1.469775 | 0.799915 | -0.602881 | -0.014654 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 9146 | 0.563927 | -0.508757 | -0.327512 | -0.637391 | -0.820638 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 9657 | 1.478779 | 0.487849 | -0.637779 | -0.648240 | -0.468778 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 9704 | 0.380957 | -0.238383 | 0.443053 | 0.670490 | 0.587128 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 9879 | 1.295809 | -0.442966 | -0.698505 | -0.494818 | -0.662602 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 9980 | 0.746898 | -1.455992 | -0.849144 | 0.592902 | -0.022726 | 1 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|

9999 rows × 22 columns
<button class="colab-df-convert" title="Convert this dataframe to an interactive table." style="display:none;"> </button>

## Process the full dataset with the distributed runner

The previous section demonstrates how to build and execute the pipeline locally using the interactive runner.
This section demonstrates how to run the pipeline on the full dataset by switching to a distributed runner. For this example, the pipeline runs on [Dataflow](https://cloud.google.com/dataflow/docs/guides/deploying-a-pipeline).

    PROJECT_ID = "<my-gcp-project>" # @param {type:'string'}
    REGION = "us-central1"
    TEMP_DIR = "gs://<my-bucket>/tmp" # @param {type:'string'}
    OUTPUT_DIR = "gs://<my-bucket>/dataframe-result" # @param {type:'string'}

These steps process the full dataset, `full.csv`, which contains approximately one million rows. To materialize the deferred DataFrame, these steps also write the results to a CSV file instead of using `ib.collect()`.

To switch from an interactive runner to a distributed runner, update the pipeline options. The rest of the pipeline steps don't change.

    # Specify the location of the source CSV file (the full dataset).
    source_csv_file = 'gs://apache-beam-samples/nasa_jpl_asteroid/full.csv'

    # Build a new pipeline that runs on Dataflow.
    p = beam.Pipeline(DataflowRunner(),
                      options=beam.options.pipeline_options.PipelineOptions(
                          project=PROJECT_ID,
                          region=REGION,
                          temp_location=TEMP_DIR,
                          # To speed up the demo, disable autoscaling.
                          autoscaling_algorithm='NONE',
                          num_workers=10))

    # Create a deferred Apache Beam DataFrame with the contents of the CSV file.
    beam_df = p | beam.dataframe.io.read_csv(source_csv_file)

    # Drop irrelevant columns and columns with missing values.
    beam_df = beam_df.drop(['spk_id', 'full_name','diameter', 'albedo', 'diameter_sigma'], axis='columns', inplace=False)

    # Get numerical columns and columns with categorical values.
    numerical_cols = beam_df.select_dtypes(include=np.number).columns.tolist()
    categorical_cols = list(set(beam_df.columns) - set(numerical_cols))

    # Normalize the numerical values. 
    beam_df_numericals = beam_df.filter(items=numerical_cols)
    beam_df_numericals = (beam_df_numericals - beam_df_numericals.mean())/beam_df_numericals.std()


    # One-hot encode the categorical values. 
    for categorical_col in categorical_cols:
      beam_df_categorical= get_one_hot_encoding(df=beam_df, categorical_col=categorical_col)
      beam_df_numericals = beam_df_numericals.merge(beam_df_categorical, left_index = True, right_index = True

    # Write the preprocessed dataset to a CSV file.
    beam_df_numericals.to_csv(os.path.join(OUTPUT_DIR, "preprocessed_data.csv"))

Submit and run the pipeline.

    p.run().wait_until_finish()

Wait while the pipeline job runs.

## What's next

This tutorial demonstrated how to analyze and preprocess a large-scale dataset with the Apache Beam DataFrames API. You can now train a model on a classification task using the preprocessed dataset.

To learn more about how to get started with classifying structured data, see
[Structured data classification from scratch](https://keras.io/examples/structured_data/structured_data_classification_from_scratch/).

To continue learning, find another dataset to use with the Apache Beam DataFrames API processing. Think carefully about which features to include in your model and how to represent them.

## Resources

- [Beam DataFrames overview](https://beam.apache.org/documentation/dsls/dataframes/overview) - An overview of the Apache Beam DataFrames API.
- [Differences from pandas](https://beam.apache.org/documentation/dsls/dataframes/differences-from-pandas) - Reviews the differences between Apache Beam DataFrames and Pandas DataFrames, as well as some of the workarounds for unsupported operations.
- [10 minutes to Pandas](https://pandas.pydata.org/pandas-docs/stable/user_guide/10min.html) - A quickstart guide to the Pandas DataFrames.
- [Pandas DataFrame API](https://pandas.pydata.org/pandas-docs/stable/reference/frame.html) - The API reference for the Pandas DataFrames.
- [Data preparation and feature training in ML](https://developers.google.com/machine-learning/data-prep) - A guideline about data transformation for ML training.