Universal Functions In Pandas
1. UNIVERSAL FUNCTIONS: INDEX PRESERVATION
All NumPy Ufunc will work on Pandas Series
and DataFrame
First, let’s create Pandas Series
of random integers
Second, create a Pandas DataFrame
of random integers
Now, if we apply any Numpy Ufunc on these objects (Series
or DataFrame
) the result will be another Panda object with indices preserved
2. UNIVERSAL FUNCTIONS: INDEX ALIGNMENT
2.1. Index Alignment in Series
When we try to add
two Series
with non-identical index, the resulting sum will keep the index alignment
As we can tell from above example, when we perform the sum, the indices of both series are preserved.
add() method with fill_value
When Python doesn’t find any corresponding value on same index, it returns
NaN
For example, in Series
A
there is index 0 but no corresponding value for SeriesB
, index 0To handle this NaN, we can use kwarg
fill_value
with Pandas.add()
method
2.2. Index Alignment in DataFrame
When we try to add
two DataFrame
with non-identical index, the resulting sum will keep the index alignment
add() method with fill_value
When Python doesn’t find any corresponding value on same index and column, it returns
NaN
For example, in DataFrame
D
there is index 0, column ‘c’ but no corresponding value for SeriesC
under index 0, column ‘c’We can use keyword argument,
fill_value
with Pandas.add()
method to handle the NaN
2.3. Python Operators and their equivalent Pandas Methods
+
add()
-
sub(),subtract()
*
mul(),multiply()
/
div(),divide(),truediv()
//
floordiv()
%
mod()
**
pow()
3. UNIVERSAL FUNCTIONS: OTHER OPERATIONS
3.1. Understanding ‘axis’ keyword argument
One way to look at axis
kwarg:
axis
kwarg:Remember that we mention, axis=0
or axis=index
the operation will be performed column wise and when we mention axis=1
or axis=column
, the operation will be performed row wise.
Another way to look at axis
kwarg:
axis
kwarg:axis=0
oraxis=index
means to perform operation on all the rows in each columnaxis=1
oraxis=column
means to perform operation on all the columns in each row
3.2. Operations on Self
Let’s subtract values of first row of the df1
from all rows in df1
. In this case, the default value of kwarg, axis
is 1
or columns
However, If we would like to apply this arithmetic operation index-wise, we can use, axis=0
or axis=index
3.3. Operation between Series and DataFrame
Operations between a DataFrame
and Series
object are similar to operations between a two-dimensional and one-dimensional NumPy array
Let add Series
to DataFrame
with kwarg, axis=0
or axis=index
, which matches the index . Both ser1
and df1
have identical index
Last updated
Was this helpful?