Book Image

Big Data Analysis with Python

By : Ivan Marin, Ankit Shukla, Sarang VK
Book Image

Big Data Analysis with Python

By: Ivan Marin, Ankit Shukla, Sarang VK

Overview of this book

Processing big data in real time is challenging due to scalability, information inconsistency, and fault tolerance. Big Data Analysis with Python teaches you how to use tools that can control this data avalanche for you. With this book, you'll learn practical techniques to aggregate data into useful dimensions for posterior analysis, extract statistical measurements, and transform datasets into features for other systems. The book begins with an introduction to data manipulation in Python using pandas. You'll then get familiar with statistical analysis and plotting techniques. With multiple hands-on activities in store, you'll be able to analyze data that is distributed on several computers by using Dask. As you progress, you'll study how to aggregate data for plots when the entire data cannot be accommodated in memory. You'll also explore Hadoop (HDFS and YARN), which will help you tackle larger datasets. The book also covers Spark and explains how it interacts with other tools. By the end of this book, you'll be able to bootstrap your own Python environment, process large files, and manipulate data to generate statistics, metrics, and graphs.
Table of Contents (11 chapters)
Big Data Analysis with Python
Preface

Chapter 02: Statistical Visualizations Using Matplotlib and Seaborn


Activity 4: Line Graphs with the Object-Oriented API and Pandas DataFrames

  1. Import the required libraries in the Jupyter notebook and read the dataset from the Auto-MPG dataset repository:

    %matplotlib inline
    import matplotlib as mpl
    import matplotlib.pyplot as pltimport numpy as np
    import pandas as pd
    
    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
    df = pd.read_csv(url)
  2. Provide the column names to simplify the dataset, as illustrated here:

    column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
  3. Now read the new dataset with column names and display it:

    df = pd.read_csv(url, names= column_names, delim_whitespace=True)
    df.head()

    The plot is as follows:

    Figure 2.29: The auto-mpg DataFrame

  4. Convert the horsepower and year data types to float and integer using the following command:

    df.loc[df.horsepower == '?', 'horsepower'] = np.nan
    df['horsepower'] = pd.to_numeric(df['horsepower'])
    df['full_date'] = pd.to_datetime(df.year, format='%y')
    df['year'] = df['full_date'].dt.year
  5. Let's display the data types:

    df.dtypes

    The output is as follows:

    Figure 2.30: The data types

  6. Now plot the average horsepower per year using the following command:

    df.groupby('year')['horsepower'].mean().plot()

    The output is as follows:

    Figure 2.31: Line plot

Activity 5: Understanding Relationships of Variables Using Scatter Plots

  1. Import the required libraries into the Jupyter notebook and read the dataset from the Auto-MPG dataset repository:

    %matplotlib inline
    import pandas as pd
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
    df = pd.read_csv(url)
  2. Provide the column names to simplify the dataset as illustrated here:

    column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
  3. Now read the new dataset with column names and display it:

    df = pd.read_csv(url, names= column_names, delim_whitespace=True)
    df.head()

    The plot is as follows:

    Figure 2.32: Auto-mpg DataFrame

  4. Now plot the scatter plot using the scatter method:

    fig, ax = plt.subplots()
    ax.scatter(x = df['horsepower'], y=df['weight'])

    The output will be as follows:

    Figure 2.33: Scatter plot using the scatter method

Activity 6: Exporting a Graph to a File on Disk

  1. Import the required libraries in the Jupyter notebook and read the dataset from the Auto-MPG dataset repository:

    %matplotlib inline
    import pandas as pd
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
    df = pd.read_csv(url)
  2. Provide the column names to simplify the dataset, as illustrated here:

    column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
  3. Now read the new dataset with column names and display it:

    df = pd.read_csv(url, names= column_names, delim_whitespace=True)
  4. Create a bar plot using the following command:

    fig, ax = plt.subplots()
    df.weight.plot(kind='hist', ax=ax)

    The output is as follows:

    Figure 2.34: Bar plot

  5. Export it to a PNG file using the savefig function:

    fig.savefig('weight_hist.png')

Activity 7: Complete Plot Design

  1. Import the required libraries in the Jupyter notebook and read the dataset from the Auto-MPG dataset repository:

    %matplotlib inline
    import pandas as pd
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
    df = pd.read_csv(url)
  2. Provide the column names to simplify the dataset, as illustrated here:

    column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
  3. Now read the new dataset with column names and display it:

    df = pd.read_csv(url, names= column_names, delim_whitespace=True)
  4. Perform GroupBy on year and cylinders, and unset the option to use them as indexes:

    df_g = df.groupby(['year', 'cylinders'], as_index=False)
  5. Calculate the average miles per gallon over the grouping and set year as index:

    df_g = df_g.mpg.mean()
  6. Set year as the DataFrame index:

    df_g = df_g.set_index(df_g.year)
  7. Create the figure and axes using the object-oriented API:

    import matplotlib.pyplot as plt
    fig, axes = plt.subplots()
  8. Group the df_g dataset by cylinders and plot the miles per gallon variable using the axes created with size (10,8):

    df = df.convert_objects(convert_numeric=True)
    df_g = df.groupby(['year', 'cylinders'], as_index=False).horsepower.mean()
    df_g = df_g.set_index(df_g.year)
  9. Set the title, x label, and y label on the axes:

    fig, axes = plt.subplots()
    df_g.groupby('cylinders').horsepower.plot(axes=axes, figsize=(12,10))
    _ = axes.set(
        title="Average car power per year",
        xlabel="Year",
        ylabel="Power (horsepower)"
        
    )

    The output is as follows:

    Figure 2.35: Line plot for average car power per year (without legends)

  10. Include legends, as follows:

    axes.legend(title='Cylinders', fancybox=True)

    Figure 2.36: Line plot for average car power per year (with legends)

  11. Save the figure to disk as a PNG file:

    fig.savefig('mpg_cylinder_year.png')