<jupyter_start><jupyter_text>Operating on Data in PandasOne of the essential pieces of NumPy is the ability to perform quick element-wise operations, both with basic arithmetic(addition, subtraction, multiplication, etc.) and with more sophisticated operations (trigonometric functions, exponential and logarithmic functions, etc.). Pandas inherits much ofthis functionality from NumPy, and the ufuncs that we introduced are the key to this.Pandas includes a couple useful twists, however: for unary operations like negation and trigonometric functions, these ufuncs will *preserve index and column labels* in the output, and for binary operations such as addition and multiplication, Pandas will automatically *align indices* when passing the objects to the ufunc. This means that keeping the context of data and combining data from different sources-both potentially error-prone tasks with raw NumPy arrays-become essentially foolproof ones with Pandas. We will additionally see that there are well-defined operations between one-dimensional `Series` structures and two-diemnsional `DataFrame` structures.  Ufuncs: Index PreservationBecasue Pandas is designed to work with NumPy, any NumPy ufunc will work on Pandas `Series` and `DataFrame` objects. Let's start by defining a simple `Series` and `DataFrame` on which to demosntrate this:<jupyter_code>import pandas as pd
import numpy as np
rng = np.random.RandomState(42)
ser = pd.Series(rng.randint(0, 10, 4))
ser
df = pd.DataFrame(rng.randint(0, 10, (3, 4)), columns=['A', 
 'B', 'C', 'D'])
df<jupyter_output><empty_output><jupyter_text>If we apply a NumPy ufunc on either of these objects, the result will be another Pandas object *with the indices preserved*:<jupyter_code>np.exp(ser)<jupyter_output><empty_output><jupyter_text>Or, for a slightly more complex calculation:<jupyter_code>np.sin(df * np.pi / 4)<jupyter_output><empty_output><jupyter_text>UFuncs: Index AlignmentFor binary operations on two `Series` or `DataFrame` objects, Pandas will align indices in the process of performingth eoperation. This is very convenient when working with incomplete data, as we'll see in some of the examples that follow.  Index alignment in Series:As an example, suppose we are combinig two different data sources, and find only the top three US states by *area* and the top three US states by *population*:<jupyter_code>area = pd.Series({'Alaska': 1723337, 'Texas': 695662, 'California': 423967}, name='area')
population = pd.Series({'California': 38332521, 'Texas': 26448193, 'New York': 19661127}, name='population')<jupyter_output><empty_output><jupyter_text>Let's see what happens when we divide these to compute the population density:<jupyter_code>population / area<jupyter_output><empty_output><jupyter_text>The resulting array contains the *union* of indices of the two input arrays, which could be determined suing standard Python set arithmetic on these indices:<jupyter_code>area.index | population.index<jupyter_output><empty_output><jupyter_text>Any item for which one or the other does not have an entry is marked with `NaN`, or "Not a Number", which is how Pandas marks missing data. this index matching is implemented this way for any of Python's ubilt-in arithmetic expressions; any missing values are filled in with NaN by default:<jupyter_code>A = pd.Series([2, 4 ,6], index=[0, 1, 2])
B = pd.Series([1, 3, 5], index=[1, 2 ,3])

A + B<jupyter_output><empty_output><jupyter_text>If using NaN values is not the desired behavior, the fil lvalue can be modified using appropriate object methods in place of the operators. For exmaple, calling `A.add(B)` is equivalent to callin `A + B`, but allows optional explicit specification of the fill value for any elements in `A` or `B` that might be missing<jupyter_code>A.add(B, fill_value=0)<jupyter_output><empty_output><jupyter_text>Index alignment in DataFrameA similar type of alignment takes place for *both* columns and indices when performing operations on `DataFrame`s:<jupyter_code>A = pd.DataFrame(rng.randint(0, 20, (2, 2)), columns=list('AB'))
A
B = pd.DataFrame(rng.randint(0, 10, (3, 3)), columns=list("BAC"))
B
A + B<jupyter_output><empty_output><jupyter_text>Notice that indices are aligned correctly irrespective of their order in the two objects, and indices in the result are sorted. As was the case with `Series`, we can use the associated object's arithmetic method and pass any desired `fill_value` to be used in place of missing entries. Here we'll fill with the mean of all values in `A` (computed by first stacking the rows of `A`):<jupyter_code>fill = A.stack().mean()
A.add(B, fill_value=fill)<jupyter_output><empty_output><jupyter_text>The following table lists Python operators and their equivalent Pandas object methods:```Python Operator 	Pandas Method(s)+ 	add()- 	sub(), subtract()* 	mul(), multiply()/ 	truediv(), div(), divide()// 	floordiv()% 	mod()** 	pow()```  Ufuncs: Operations Between DataFrame and SeriesWhen performing operations between a `DataFrame` and a `Series`, the index and column alignment is similarly maintained. Operations between a `DataFrame` and a `Series` are similar to operations between a two-dimensional and one-dimensional NumPy array. Consider one common operation, where we find the difference of a two-dimesional array and one of its rows:<jupyter_code>A = rng.randint(10, size=(3, 4))
A
A - A[0]<jupyter_output><empty_output><jupyter_text>According to NumPy's broadcasting rules, substraction between a two-dimensional array and one of its rows is applied row-wise.In Pandas, the convention similary operates row-wise by default:<jupyter_code>df = pd.DataFrame(A, columns=list('QRST'))
df - df.iloc[0]<jupyter_output><empty_output><jupyter_text>If you would instead like to operate column-wise, you can use the object methods mentioned earlier, while specifying the `axis` keyword:<jupyter_code>df.subtract(df['R'], axis=0)<jupyter_output><empty_output><jupyter_text>Note that hese `DataFrame`/`Series` operations, like the operations discussed above, will automatically align indices between the two elements:<jupyter_code>halfrow = df.iloc[0,::2]
halfrow
df - halfrow<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08886370993849142, 'fraction_numerical': 0.014082227258012302, 'mean_word_length': 6.2779740871613665, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 57, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '454266', 'license': 'MIT', 'n_tokens_mistral': 1883, 'n_tokens_neox': 1771, 'n_words': 741, 'path': 'pandas/operating_on_data.ipynb', 'repo_name': 'Jeffresh/python-datascience-handbook', 'size': '6178'}