Arithmetic on a DataFrame

Arithmetic operations using scalar values will be applied to every element of a DataFrame. To demonstrate, we will use a DataFrame object initialized with random values:

In [94]:
   # set the seed to allow replicatable results
   np.random.seed(123456)
   # create the DataFrame
   df = pd.DataFrame(np.random.randn(5, 4), 
                     columns=['A', 'B', 'C', 'D'])
   df

Out[94]:
             A         B         C         D
   0  0.469112 -0.282863 -1.509059 -1.135632
   1  1.212112 -0.173215  0.119209 -1.044236
   2 -0.861849 -2.104569 -0.494929  1.071804
   3  0.721555 -0.706771 -1.039575  0.271860
   4 -0.424972  0.567020  0.276232 -1.087401

By default, any arithmetic operation will be applied across all rows and columns of a DataFrame and will return a new DataFrame with the results (leaving ...

Get Learning pandas now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.