How to apply numerical functions and operations to Series and DataFrame objects
In the following section, we will see how to apply numerical functions and operations to Series
and DataFrame
objects.
Getting ready
When a DataFrame
operates directly with one of the arithmetic or comparison operators, each value of each column gets the operation applied to it. Typically, when an operator is used with a DataFrame
, the columns are either all numeric or all object (usually strings). If the DataFrame
does not contain homogeneous data, then the operation is likely to fail. Let's see an example of this failure with the college dataset, which contains both numeric and object data types. Attempting to add 5
to each value of the DataFrame
raises a TypeError
, as integers cannot be added to strings:
college = pd.read_csv('data/college.csv') college + 5 TypeError: Could not operate 5 with block values must be str, not int
To successfully use an operator with a DataFrame
, first select homogeneous data. For...