Simple Mathematics Operations in Python/v3

Learn how to perform simple mathematical operations on dataframes such as scaling, adding, and subtracting


Note: this page is part of the documentation for version 3 of Plotly.py, which is not the most recent version.
See our Version 4 Migration Guide for information about how to upgrade.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Imports

The tutorial below imports NumPy, Pandas, and SciPy.

In [1]:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

import numpy as np
import pandas as pd
import scipy

Import Data

Let us import a timeseries dataset to perform mathematical operations on:

In [2]:
data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/timeseries.csv')

table = FF.create_table(data)
py.iplot(table, filename='timeseries-data-table')
Out[2]:

Scale a Dataset

You can modify a dataset by scaling each number by a constant.

In [3]:
x = data['Date']
y = data['A']
y2 = [2.*k for k in y]

trace1 = go.Scatter(
    x=x,
    y=y,
    mode='markers',
    name='Data',
    marker=dict(
        size=12
    )
)

trace2 = go.Scatter(
    x=x,
    y=y2,
    mode='markers',
    name='Scaled by 2',
    marker=dict(
        size=12,
        symbol='x'
    )
)

trace_data = [trace1, trace2]
py.iplot(trace_data, filename='scale-a-dataset')
Out[3]:

Subtract Two Columns

In [4]:
trace1 = go.Scatter(
    x=data['Date'],
    y=data['A'],
    mode='markers',
    name='Column A',
    marker=dict(
        size=12
    )
)

trace2 = go.Scatter(
    x=data['Date'],
    y=data['D'],
    mode='markers',
    name='Column D',
    marker=dict(
        size=12
    )
)

trace3 = go.Scatter(
    x=data['Date'],
    y=data['D'] - data['A'],
    mode='markers',
    name='Column D - Column A',
    marker=dict(
        size=12,
        symbol='square-open'
    )
)

trace_data1 = [trace1, trace2, trace3]
py.iplot(trace_data1, filename='subtract-two-dataframe-columns')
Out[4]:

Modify DataFrame Entries

Use arithmetic operations including addition, subtraction, multiplication and division to change the values in a DataFrame column:

In [5]:
dataframe = pd.DataFrame([[1, 2],
                          [3, 4],
                          [5, 6],
                          [7, 8]],
                         columns=['A', 'B'])

table = FF.create_table(dataframe)
py.iplot(table, filename='math-operations-dataframe')
Out[5]:
In [6]:
dataframe['A'][0] = 120
dataframe['B'][3] = -2*dataframe['B'][3]

table = FF.create_table(dataframe)
py.iplot(table, filename='math-operations-dataframe-changed')
Out[6]: