Panda Series

class pandas.Series(data=Noneindex=Nonedtype=Nonename=Nonecopy=Falsefastpath=False)[source]

One-dimensional ndarray with axis labels (including time series).

Labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Statistical methods from ndarray have been overridden to automatically exclude missing data (currently represented as NaN).

Operations between Series (+, -, /, , *) align values based on their associated index values– they need not be the same length. The resulting index will be the sorted union of the two indexes. Parametersdataarray-like, Iterable, dict, or scalar value

Contains data stored in Series. If data is a dict, argument order is maintained.indexarray-like or Index (1d)

Values must be hashable and have the same length as data. Non-unique index values are allowed. Will default to RangeIndex (0, 1, 2, …, n) if not provided. If data is dict-like and index is None, then the values in the index are used to reindex the Series after it is created using the keys in the data.dtypestr, numpy.dtype, or ExtensionDtype, optional

Data type for the output Series. If not specified, this will be inferred from data. See the user guide for more usages.namestr, optional

The name to give to the Series.copybool, default False

Copy input data.

Attributes

S.NFunctionMeaning
1TReturn the transpose, which is by definition self.
2arrayThe ExtensionArray of the data backing this Series or Index.
3atAccess a single value for a row/column label pair.
4attrsDictionary of global attributes of this dataset.
5axesReturn a list of the row axis labels.
6dtypeReturn the dtype object of the underlying data.
7dtypesReturn the dtype object of the underlying data.
8flagsGet the properties associated with this pandas object.
9hasnansReturn if I have any nans; enables various perf speedups.
10iatAccess a single value for a row/column pair by integer position.
11ilocPurely integer-location based indexing for selection by position.
12indexThe index (axis labels) of the Series.
13is_monotonicReturn boolean if values in the object are monotonic_increasing.
14is_monotonic_decreasingReturn boolean if values in the object are monotonic_decreasing.
15is_monotonic_increasingAlias for is_monotonic.
16is_uniqueReturn boolean if values in the object are unique.
17locAccess a group of rows and columns by label(s) or a boolean array.
18nameReturn the name of the Series.
19nbytesReturn the number of bytes in the underlying data.
20ndimNumber of dimensions of the underlying data, by definition 1.
21shapeReturn a tuple of the shape of the underlying data.
22sizeReturn the number of elements in the underlying data.
23valuesReturn Series as ndarray or ndarray-like depending on the type.

1. pandas.Series.T

property Series.T

Return the transpose, which is by definition self.

2. pandas.Series.array

property Series.array

The ExtensionArray of the data backing this Series or Index.ReturnsExtensionArray

An ExtensionArray of the values stored within. For extension types, this is the actual array. For NumPy native types, this is a thin (no copy) wrapper around numpy.ndarray.

.array differs .values which may require converting the data to a different form.

3. pandas.Series.at

property Series.at

Access a single value for a row/column label pair.

Similar to loc, in that both provide label-based lookups. Use at if you only need to get or set a single value in a DataFrame or Series.RaisesKeyError

If ‘label’ does not exist in DataFrame.

4. pandas.Series.attrs

property Series.attrs

Dictionary of global attributes of this dataset.

5. pandas.Series.axes

property Series.axes

Return a list of the row axis labels.

6.pandas.Series.dtype

property Series.dtype

Return the dtype object of the underlying data.

7.pandas.Series.dtypes

property Series.dtypes

Return the dtype object of the underlying data.

8. pandas.Series.flags

property Series.flags

Get the properties associated with this pandas object.

The available flags are

9. pandas.Series.hasnans

property Series.hasnans

Return True if there are any NaNs.

Enables various performance speedups.

10. pandas.Series.iat

property Series.iat

Access a single value for a row/column pair by integer position.

Similar to iloc, in that both provide integer-based lookups. Use iat if you only need to get or set a single value in a DataFrame or Series.RaisesIndexError

When integer position is out of bounds.

11. pandas.Series.iloc

property Series.iloc

Purely integer-location based indexing for selection by position.

.iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array.

Allowed inputs are:

  • An integer, e.g. 5.
  • A list or array of integers, e.g. [4, 3, 0].
  • A slice object with ints, e.g. 1:7.
  • A boolean array.
  • callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). This is useful in method chains, when you don’t have a reference to the calling object, but would like to base your selection on some value.

.iloc will raise IndexError if a requested indexer is out-of-bounds, except slice indexers which allow out-of-bounds indexing (this conforms with python/numpy slice semantics).

12. pandas.Series.index

Series.index

The index (axis labels) of the Series.

13. pandas.Series.is_monotonic

property Series.is_monotonic

Return boolean if values in the object are monotonic_increasing.Returns bool

14. pandas.Series.is_monotonic_decreasing

property Series.is_monotonic_decreasing

Return boolean if values in the object are monotonic_decreasing.Returns bool

15. pandas.Series.is_monotonic_increasing

property Series.is_monotonic_increasing

Alias for is_monotonic.

16. pandas.Series.is_unique

property Series.is_unique

Return boolean if values in the object are unique.
Returns bool

17. pandas.Series.loc

property Series.loc

Access a group of rows and columns by label(s) or a boolean array.

.loc[] is primarily label based, but may also be used with a boolean array.

Allowed inputs are:

  • A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index).
  • A list or array of labels, e.g. ['a', 'b', 'c'].
  • A slice object with labels, e.g. 'a':'f'.WarningNote that contrary to usual python slices, both the start and the stop are included
  • A boolean array of the same length as the axis being sliced, e.g. [True, False, True].
  • An alignable boolean Series. The index of the key will be aligned before masking.
  • An alignable Index. The Index of the returned selection will be the input.
  • callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above)

See more at Selection by Label.RaisesKeyError

If any items are not found.IndexingError

If an indexed key is passed and its index is unalignable to the frame index.

18. pandas.Series.name

property Series.name

Return the name of the Series.

The name of a Series becomes its index or column name if it is used to form a DataFrame. It is also used whenever displaying the Series using the interpreter.Returnslabel (hashable object)

The name of the Series, also the column name if part of a DataFrame.

See alsoSeries.rename

Sets the Series name when given a scalar input.Index.name

Corresponding Index property.

Examples

The Series name can be set initially when calling the constructor.

>>> s = pd.Series([1, 2, 3], dtype=np.int64, name='Numbers')
>>> s
0    1
1    2
2    3
Name: Numbers, dtype: int64
>>> s.name = "Integers"
>>> s
0    1
1    2
2    3
Name: Integers, dtype: int64

The name of a Series within a DataFrame is its column name.

>>> df = pd.DataFrame([[1, 2], [3, 4], [5, 6]],
...                   columns=["Odd Numbers", "Even Numbers"])
>>> df
   Odd Numbers  Even Numbers
0            1             2
1            3             4
2            5             6
>>> df["Even Numbers"].name
'Even Numbers'

19. pandas.Series.nbytes

property Series.nbytes

Return the number of bytes in the underlying data.

20. pandas.Series.ndim

property Series.ndim

Number of dimensions of the underlying data, by definition 1.

21. pandas.Series.shape

property Series.shape

Return a tuple of the shape of the underlying data.

22. pandas.Series.size

property Series.size

Return the number of elements in the underlying data.

23. pandas.Series.values

property Series.values

Return Series as ndarray or ndarray-like depending on the dtype.

Warning

We recommend using Series.array or Series.to_numpy(), depending on whether you need a reference to the underlying data or a NumPy array.Returnsnumpy.ndarray or ndarray-like

See alsoSeries.array

Reference to the underlying data.Series.to_numpy

A NumPy array representing the underlying data.

Examples

>>> pd.Series([1, 2, 3]).values
array([1, 2, 3])
>>> pd.Series(list('aabc')).values
array(['a', 'a', 'b', 'c'], dtype=object)
>>> pd.Series(list('aabc')).astype('category').values
['a', 'a', 'b', 'c']
Categories (3, object): ['a', 'b', 'c']

Timezone aware datetime data is converted to UTC:

>>> pd.Series(pd.date_range('20130101', periods=3,
...                         tz='US/Eastern')).values
array(['2013-01-01T05:00:00.000000000',
       '2013-01-02T05:00:00.000000000',
       '2013-01-03T05:00:00.000000000'], dtype='datetime64[ns]')

Methods

S.NMethodMeaning
1abs()Return a Series/DataFrame with absolute numeric value of each element.
2add(other[, level, fill_value, axis])Return Addition of series and other, element-wise (binary operator add).
3add_prefix(prefix)Prefix labels with string prefix.
4add_suffix(suffix)Suffix labels with string suffix.
5agg([func, axis])Aggregate using one or more operations over the specified axis.
6aggregate([func, axis])Aggregate using one or more operations over the specified axis.
7align(other[, join, axis, level, copy, …])Align two objects on their axes with the specified join method.
8all([axis, bool_only, skipna, level])Return whether all elements are True, potentially over an axis.
9any([axis, bool_only, skipna, level])Return whether any element is True, potentially over an axis.
10append(to_append[, ignore_index, …])Concatenate two or more Series.
11apply(func[, convert_dtype, args])Invoke function on values of Series.
12argmax([axis, skipna])Return int position of the largest value in the Series.
13argmin([axis, skipna])Return int position of the smallest value in the Series.
14argsort([axis, kind, order])Return the integer indices that would sort the Series values.
15asfreq(freq[, method, how, normalize, …])Convert TimeSeries to specified frequency.
16asof(where[, subset])Return the last row(s) without any NaNs before where.
17astype(dtype[, copy, errors])Cast a pandas object to a specified dtype dtype.
18at_time(time[, asof, axis])Select values at particular time of day (e.g., 9:30AM).
19autocorr([lag])Compute the lag-N autocorrelation.
20backfill([axis, inplace, limit, downcast])Synonym for DataFrame.fillna() with method='bfill'.
21between(left, right[, inclusive])Return boolean Series equivalent to left <= series <= right.
22between_time(start_time, end_time[, …])Select values between particular times of the day (e.g., 9:00-9:30 AM).
23bfill([axis, inplace, limit, downcast])Synonym for DataFrame.fillna() with method='bfill'.
24bool()Return the bool of a single element Series or DataFrame.
25catalias of pandas.core.arrays.categorical.CategoricalAccessor
26clip([lower, upper, axis, inplace])Trim values at input threshold(s).
27combine(other, func[, fill_value])Combine the Series with a Series or scalar according to func.
28combine_first(other)Combine Series values, choosing the calling Series’s values first.
29compare(other[, align_axis, keep_shape, …])Compare to another Series and show the differences.
30convert_dtypes([infer_objects, …])Convert columns to best possible dtypes using dtypes supporting pd.NA.
31copy([deep])Make a copy of this object’s indices and data.
32corr(other[, method, min_periods])Compute correlation with other Series, excluding missing values.
33count([level])Return number of non-NA/null observations in the Series.
34cov(other[, min_periods, ddof])Compute covariance with Series, excluding missing values.
35cummax([axis, skipna])Return cumulative maximum over a DataFrame or Series axis.
36cummin([axis, skipna])Return cumulative minimum over a DataFrame or Series axis.
37cumprod([axis, skipna])Return cumulative product over a DataFrame or Series axis.
38cumsum([axis, skipna])Return cumulative sum over a DataFrame or Series axis.
39describe([percentiles, include, exclude, …])Generate descriptive statistics.
40diff([periods])First discrete difference of element.
41div(other[, level, fill_value, axis])Return Floating division of series and other, element-wise (binary operator truediv).
42divide(other[, level, fill_value, axis])Return Floating division of series and other, element-wise (binary operator truediv).
43divmod(other[, level, fill_value, axis])Return Integer division and modulo of series and other, element-wise (binary operator divmod).
44dot(other)Compute the dot product between the Series and the columns of other.
45drop([labels, axis, index, columns, level, …])Return Series with specified index labels removed.
46drop_duplicates([keep, inplace])Return Series with duplicate values removed.
47droplevel(level[, axis])Return DataFrame with requested index / column level(s) removed.
48dropna([axis, inplace, how])Return a new Series with missing values removed.
49dtalias of pandas.core.indexes.accessors.CombinedDatetimelikeProperties
50duplicated([keep])Indicate duplicate Series values.
51eq(other[, level, fill_value, axis])Return Equal to of series and other, element-wise (binary operator eq).
52equals(other)Test whether two objects contain the same elements.
53ewm([com, span, halflife, alpha, …])Provide exponential weighted (EW) functions.
54expanding([min_periods, center, axis])Provide expanding transformations.
55explode([ignore_index])Transform each element of a list-like to a row.
56factorize([sort, na_sentinel])Encode the object as an enumerated type or categorical variable.
57ffill([axis, inplace, limit, downcast])Synonym for DataFrame.fillna() with method='ffill'.
58fillna([value, method, axis, inplace, …])Fill NA/NaN values using the specified method.
59filter([items, like, regex, axis])Subset the dataframe rows or columns according to the specified index labels.
60first(offset)Select initial periods of time series data based on a date offset.
61first_valid_index()Return index for first non-NA/null value.
62floordiv(other[, level, fill_value, axis])Return Integer division of series and other, element-wise (binary operator floordiv).
63ge(other[, level, fill_value, axis])Return Greater than or equal to of series and other, element-wise (binary operator ge).
64get(key[, default])Get item from object for given key (ex: DataFrame column).
65groupby([by, axis, level, as_index, sort, …])Group Series using a mapper or by a Series of columns.
66gt(other[, level, fill_value, axis])Return Greater than of series and other, element-wise (binary operator gt).
67head([n])Return the first n rows.
68hist([by, ax, grid, xlabelsize, xrot, …])Draw histogram of the input series using matplotlib.
69idxmax([axis, skipna])Return the row label of the maximum value.
70idxmin([axis, skipna])Return the row label of the minimum value.
71infer_objects()Attempt to infer better dtypes for object columns.
72interpolate([method, axis, limit, inplace, …])Fill NaN values using an interpolation method.
73isin(values)Whether elements in Series are contained in values.
74isna()Detect missing values.
75isnull()Detect missing values.
76item()Return the first element of the underlying data as a Python scalar.
77items()Lazily iterate over (index, value) tuples.
78iteritems()Lazily iterate over (index, value) tuples.
79keys()Return alias for index.
80kurt([axis, skipna, level, numeric_only])Return unbiased kurtosis over requested axis.
81kurtosis([axis, skipna, level, numeric_only])Return unbiased kurtosis over requested axis.
82last(offset)Select final periods of time series data based on a date offset.
83last_valid_index()Return index for last non-NA/null value.
84le(other[, level, fill_value, axis])Return Less than or equal to of series and other, element-wise (binary operator le).
85lt(other[, level, fill_value, axis])Return Less than of series and other, element-wise (binary operator lt).
86mad([axis, skipna, level])Return the mean absolute deviation of the values over the requested axis.
87map(arg[, na_action])Map values of Series according to input correspondence.
88mask(cond[, other, inplace, axis, level, …])Replace values where the condition is True.
89max([axis, skipna, level, numeric_only])Return the maximum of the values over the requested axis.
90mean([axis, skipna, level, numeric_only])Return the mean of the values over the requested axis.
91median([axis, skipna, level, numeric_only])Return the median of the values over the requested axis.
92memory_usage([index, deep])Return the memory usage of the Series.
93min([axis, skipna, level, numeric_only])Return the minimum of the values over the requested axis.
94mod(other[, level, fill_value, axis])Return Modulo of series and other, element-wise (binary operator mod).
95mode([dropna])Return the mode(s) of the Series.
96mul(other[, level, fill_value, axis])Return Multiplication of series and other, element-wise (binary operator mul).
97multiply(other[, level, fill_value, axis])Return Multiplication of series and other, element-wise (binary operator mul).
98ne(other[, level, fill_value, axis])Return Not equal to of series and other, element-wise (binary operator ne).
99nlargest([n, keep])Return the largest n elements.
100notna()Detect existing (non-missing) values.
101notnull()Detect existing (non-missing) values.
102nsmallest([n, keep])Return the smallest n elements.
103nunique([dropna])Return number of unique elements in the object.
104pad([axis, inplace, limit, downcast])Synonym for DataFrame.fillna() with method='ffill'.
105pct_change([periods, fill_method, limit, freq])Percentage change between the current and a prior element.
106pipe(func, *args, **kwargs)Apply func(self, *args, **kwargs).
107plotalias of pandas.plotting._core.PlotAccessor
108pop(item)Return item and drops from series.
109pow(other[, level, fill_value, axis])Return Exponential power of series and other, element-wise (binary operator pow).
110prod([axis, skipna, level, numeric_only, …])Return the product of the values over the requested axis.
111product([axis, skipna, level, numeric_only, …])Return the product of the values over the requested axis.
112quantile([q, interpolation])Return value at the given quantile.
113radd(other[, level, fill_value, axis])Return Addition of series and other, element-wise (binary operator radd).
114rank([axis, method, numeric_only, …])Compute numerical data ranks (1 through n) along axis.
115ravel([order])Return the flattened underlying data as an ndarray.
116rdiv(other[, level, fill_value, axis])Return Floating division of series and other, element-wise (binary operator rtruediv).
117rdivmod(other[, level, fill_value, axis])Return Integer division and modulo of series and other, element-wise (binary operator rdivmod).
118reindex([index])Conform Series to new index with optional filling logic.
119reindex_like(other[, method, copy, limit, …])Return an object with matching indices as other object.
120rename([index, axis, copy, inplace, level, …])Alter Series index labels or name.
121rename_axis([mapper, index, columns, axis, …])Set the name of the axis for the index or columns.
122reorder_levels(order)Rearrange index levels using input order.
123repeat(repeats[, axis])Repeat elements of a Series.
124replace([to_replace, value, inplace, limit, …])Replace values given in to_replace with value.
125resample(rule[, axis, closed, label, …])Resample time-series data.
126reset_index([level, drop, name, inplace])Generate a new DataFrame or Series with the index reset.
127rfloordiv(other[, level, fill_value, axis])Return Integer division of series and other, element-wise (binary operator rfloordiv).
128rmod(other[, level, fill_value, axis])Return Modulo of series and other, element-wise (binary operator rmod).
129rmul(other[, level, fill_value, axis])Return Multiplication of series and other, element-wise (binary operator rmul).
130rolling(window[, min_periods, center, …])Provide rolling window calculations.
131round([decimals])Round each value in a Series to the given number of decimals.
132rpow(other[, level, fill_value, axis])Return Exponential power of series and other, element-wise (binary operator rpow).
133rsub(other[, level, fill_value, axis])Return Subtraction of series and other, element-wise (binary operator rsub).
134rtruediv(other[, level, fill_value, axis])Return Floating division of series and other, element-wise (binary operator rtruediv).
135sample([n, frac, replace, weights, …])Return a random sample of items from an axis of object.
136searchsorted(value[, side, sorter])Find indices where elements should be inserted to maintain order.
137sem([axis, skipna, level, ddof, numeric_only])Return unbiased standard error of the mean over requested axis.
138set_axis(labels[, axis, inplace])Assign desired index to given axis.
139set_flags(*[, copy, allows_duplicate_labels])Return a new object with updated flags.
140shift([periods, freq, axis, fill_value])Shift index by desired number of periods with an optional time freq.
141skew([axis, skipna, level, numeric_only])Return unbiased skew over requested axis.
142slice_shift([periods, axis])(DEPRECATED) Equivalent to shift without copying data.
143sort_index([axis, level, ascending, …])Sort Series by index labels.
144sort_values([axis, ascending, inplace, …])Sort by the values.
145sparsealias of pandas.core.arrays.sparse.accessor.SparseAccessor
146squeeze([axis])Squeeze 1 dimensional axis objects into scalars.
147std([axis, skipna, level, ddof, numeric_only])Return sample standard deviation over requested axis.
148stralias of pandas.core.strings.accessor.StringMethods
149sub(other[, level, fill_value, axis])Return Subtraction of series and other, element-wise (binary operator sub).
150subtract(other[, level, fill_value, axis])Return Subtraction of series and other, element-wise (binary operator sub).
151sum([axis, skipna, level, numeric_only, …])Return the sum of the values over the requested axis.
152swapaxes(axis1, axis2[, copy])Interchange axes and swap values axes appropriately.
153swaplevel([i, j, copy])Swap levels i and j in a MultiIndex.
154tail([n])Return the last n rows.
155take(indices[, axis, is_copy])Return the elements in the given positional indices along an axis.
156to_clipboard([excel, sep])Copy object to the system clipboard.
157to_csv([path_or_buf, sep, na_rep, …])Write object to a comma-separated values (csv) file.
158to_dict([into])Convert Series to {label -> value} dict or dict-like object.
159to_excel(excel_writer[, sheet_name, na_rep, …])Write object to an Excel sheet.
160to_frame([name])Convert Series to DataFrame.
161to_hdf(path_or_buf, key[, mode, complevel, …])Write the contained data to an HDF5 file using HDFStore.
162to_json([path_or_buf, orient, date_format, …])Convert the object to a JSON string.
163to_latex([buf, columns, col_space, header, …])Render object to a LaTeX tabular, longtable, or nested table/tabular.
164to_list()Return a list of the values.
165to_markdown([buf, mode, index, storage_options])Print Series in Markdown-friendly format.
166to_numpy([dtype, copy, na_value])A NumPy ndarray representing the values in this Series or Index.
167to_period([freq, copy])Convert Series from DatetimeIndex to PeriodIndex.
168to_pickle(path[, compression, protocol, …])Pickle (serialize) object to file.
169to_sql(name, con[, schema, if_exists, …])Write records stored in a DataFrame to a SQL database.
170to_string([buf, na_rep, float_format, …])Render a string representation of the Series.
171to_timestamp([freq, how, copy])Cast to DatetimeIndex of Timestamps, at beginning of period.
172to_xarray()Return an xarray object from the pandas object.
173tolist()Return a list of the values.
174transform(func[, axis])Call func on self producing a Series with transformed values.
175transpose(*args, **kwargs)Return the transpose, which is by definition self.
176truediv(other[, level, fill_value, axis])Return Floating division of series and other, element-wise (binary operator truediv).
177truncate([before, after, axis, copy])Truncate a Series or DataFrame before and after some index value.
178tshift([periods, freq, axis])(DEPRECATED) Shift the time index, using the index’s frequency if available.
179tz_convert(tz[, axis, level, copy])Convert tz-aware axis to target time zone.
180tz_localize(tz[, axis, level, copy, …])Localize tz-naive index of a Series or DataFrame to target time zone.
181unique()Return unique values of Series object.
182unstack([level, fill_value])Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.
183update(other)Modify Series in place using values from passed Series.
184value_counts([normalize, sort, ascending, …])Return a Series containing counts of unique values.
185var([axis, skipna, level, ddof, numeric_only])Return unbiased variance over requested axis.
186view([dtype])Create a new view of the Series.
187where(cond[, other, inplace, axis, level, …])Replace values where the condition is False.
188xs(key[, axis, level, drop_level])Return cross-section from the Series/DataFrame.

1.pandas.Series.add

Series.add(otherlevel=Nonefill_value=Noneaxis=0)[source]

Return Addition of series and other, element-wise (binary operator add).

Equivalent to series + other, but with support to substitute a fill_value for missing data in either one of the inputs.ParametersotherSeries or scalar valuefill_valueNone or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.levelint or name

Broadcast across a level, matching Index values on the passed MultiIndex level.ReturnsSeries

The result of the operation.

See alsoSeries.radd

Reverse of the Addition operator, see Python documentation for more details.

Examples

>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.add(b, fill_value=0)
a    2.0
b    1.0
c    1.0
d    1.0
e    NaN
dtype: float64

2.pandas.Series.add

Series.add(otherlevel=Nonefill_value=Noneaxis=0)[source]

Return Addition of series and other, element-wise (binary operator add).

Equivalent to series + other, but with support to substitute a fill_value for missing data in either one of the inputs.ParametersotherSeries or scalar valuefill_valueNone or float value, default None (NaN)

Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing.levelint or name

Broadcast across a level, matching Index values on the passed MultiIndex level.ReturnsSeries

The result of the operation.

See alsoSeries.radd

Reverse of the Addition operator, see Python documentation for more details.

Examples

>>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd'])
>>> a
a    1.0
b    1.0
c    1.0
d    NaN
dtype: float64
>>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e'])
>>> b
a    1.0
b    NaN
d    1.0
e    NaN
dtype: float64
>>> a.add(b, fill_value=0)
a    2.0
b    1.0
c    1.0
d    1.0
e    NaN
dtype: float64

3.pandas.Series.add_prefix

Series.add_prefix(prefix)[source]

Prefix labels with string prefix.

For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed.Parametersprefixstr

The string to add before each label.ReturnsSeries or DataFrame

New Series or DataFrame with updated labels.

See alsoSeries.add_suffix

Suffix row labels with string suffix.DataFrame.add_suffix

Suffix column labels with string suffix.

Examples

>>> s = pd.Series([1, 2, 3, 4])
>>> s
0    1
1    2
2    3
3    4
dtype: int64
>>> s.add_prefix('item_')
item_0    1
item_1    2
item_2    3
item_3    4
dtype: int64
>>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
>>> df
   A  B
0  1  3
1  2  4
2  3  5
3  4  6
>>> df.add_prefix('col_')
     col_A  col_B
0       1       3
1       2       4
2       3       5
3       4       6

4.pandas.Series.add_suffix

Series.add_suffix(suffix)[source]

Suffix labels with string suffix.

For Series, the row labels are suffixed. For DataFrame, the column labels are suffixed.Parameterssuffixstr

The string to add after each label.ReturnsSeries or DataFrame

New Series or DataFrame with updated labels.

See alsoSeries.add_prefix

Prefix row labels with string prefix.DataFrame.add_prefix

Prefix column labels with string prefix.

Examples

>>> s = pd.Series([1, 2, 3, 4])
>>> s
0    1
1    2
2    3
3    4
dtype: int64
>>> s.add_suffix('_item')
0_item    1
1_item    2
2_item    3
3_item    4
dtype: int64
>>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})
>>> df
   A  B
0  1  3
1  2  4
2  3  5
3  4  6
>>> df.add_suffix('_col')
     A_col  B_col
0       1       3
1       2       4
2       3       5
3       4       6



Chewing data Efficiently with NumPy and intelligently with SciPy

In this following tutorial we will learn about Chewing data Efficiently with NumPy and intelligently with SciPy and the NumPy. Let us quickly walk through some basic NumPy examples and then take a look at what SciPy provides on top of it. On the way, we will get our feet wet with plotting using the marvelous Matplotlib package.
You will fnd more interesting examples of what NumPy can offer at

    http://www.scipy.org/Tentative_NumPy_Tutorial.

You will also fnd the book NumPy Beginner’s Guide – Second Edition, Ivan Idris,Packt Publishing very valuable. Additional tutorial style guides are at http://scipy-lectures.github.com; you may also visit the offcial SciPy tutorial at http://docs.scipy.org/doc/scipy/reference/tutorial.


In this blog, we will use NumPy Version 1.6.2 and SciPy Version 0.11.0.
Learning NumPy
So let us import NumPy and play a bit with it. For that, we need to start the Python
interactive shell.

      >>> import numpy
>>> numpy.version.full_version
1.6.2

As we do not want to pollute our namespace, we certainly should not do the following:

      >>> from numpy import *


The numpy.array array will potentially shadow the array package that is included


in standard Python. Instead, we will use the following convenient shortcut:

>> import numpy as np
>>> a = np.array([0,1,2,3,4,5])
>>> a
array([0, 1, 2, 3, 4, 5])
>>> a.ndim
1
>>> a.shape
(6,)


We just created an array in a similar way to how we would create a list in Python.However, NumPy arrays have additional information about the shape. In this case,it is a one-dimensional array of fve elements. No surprises so far.


We can now transform this array in to a 2D matrix.
>>> b = a.reshape((3,2))
>>> b
array([[0, 1],
[2, 3],
[4, 5]])
>>> b.ndim
2
>>> b.shape
(3, 2)



The funny thing starts when we realize just how much the NumPy package is
optimized. For example, it avoids copies wherever possible.

>> b[1][0]=77
>>> b
array([[ 0, 1],
[77, 3],
[ 4, 5]])
>>> a
array([ 0, 1, 77, 3, 4, 5])


In this case, we have modifed the value 2 to 77 in b, and we can immediately see
the same change reflected in
a as well. Keep that in mind whenever you need a
true copy.

>> c = a.reshape((3,2)).copy()
>>> c
array([[ 0, 1],
[77, 3],
[ 4, 5]])
>>> c[0][0] = -99
>>> a
array([ 0, 1, 77, 3, 4, 5])
>>> c
array([[-99, 1],
[ 77, 3],
[ 4, 5]])


Here, c and a are totally independent copies.
Another big advantage of NumPy arrays is that the operations are propagated
to the individual elements.

>> a*2
array([ 2, 4, 6, 8, 10])
>>> a**2
array([ 1, 4, 9, 16, 25])
Contrast that to ordinary Python lists:
>>> [1,2,3,4,5]*2
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> [1,2,3,4,5]**2
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): ‘list’ and
‘int’


Of course, by using NumPy arrays we sacrifce the agility Python lists offer. Simple
operations like adding or removing are a bit complex for NumPy arrays. Luckily,
we have both at our disposal, and we will use the right one for the task at hand.
Indexing


Part of the power of NumPy comes from the versatile ways in which its arrays can
be accessed.
In addition to normal list indexing, it allows us to use arrays themselves as indices.

>> a[np.array([2,3,4])]
array([77, 3, 4])
In addition to the fact that conditions are now propagated to the individual elements,
we gain a very convenient way to access our data.
>>> a>4
array([False, False, True, False, False, True], dtype=bool)
>>> a[a>4]
array([77, 5])
This can also be used to trim outliers.
>>> a[a>4] = 4
>>> a
array([0, 1, 4, 3, 4, 4])


As this is a frequent use case, there is a special clip function for it, clipping the values
at both ends of an interval with one function call as follows:

>> a.clip(0,4)
array([0, 1, 4, 3, 4, 4])

 

Handling non-existing values
The power of NumPy’s indexing capabilities comes in handy when pre processing data that we have just read in from a text fle. It will most likely contain invalid values, which we will mark as not being a real number using numpy.NAN as follows:

c = np.array([1, 2, np.NAN, 3, 4]) # let’s pretend we have read this
from a text file
>>> c
array([ 1., 2., nan, 3., 4.])
>>> np.isnan(c)
array([False, False, True, False, False], dtype=bool)

>>> c[~np.isnan(c)]
array([ 1., 2., 3., 4.])
>>> np.mean(c[~np.isnan(c)])
2.5


Comparing runtime behaviors Let us compare the runtime behavior of NumPy with normal Python lists. In the
ollowing code, we will calculate the sum of all squared numbers of 1 to 1000 and see how much time the calculation will take. We do it 10000 times and report the total time so that our measurement is accurate enough.

import timeit
normal_py_sec = timeit.timeit(‘sum(x*x for x in xrange(1000))’,
number=10000)
naive_np_sec = timeit.timeit(‘sum(na*na)’,
setup=”import numpy as np; na=np.
arange(1000)”,
number=10000)
good_np_sec = timeit.timeit(‘na.dot(na)’,
setup=”import numpy as np; na=np.
arange(1000)”,
number=10000)
print(“Normal Python: %f sec”%normal_py_sec)
print(“Naive NumPy: %f sec”%naive_np_sec)
print(“Good NumPy: %f sec”%good_np_sec)
Normal Python: 1.157467 sec
Naive NumPy: 4.061293 sec
Good NumPy: 0.033419 sec


We make two interesting observations. First, just using NumPy as data storage (Naive NumPy) takes 3.5 times longer, which is surprising since we believe it must be much faster as it is written as a C extension. One reason for this is that the access of individual elements from Python itself is rather costly. Only when we are able to apply algorithms inside the optimized extension code do we get speed improvements, and
tremendous ones at that: using the
dot() function of NumPy, we are more than 25 times faster. In summary, in every algorithm we are about to implement, we should always look at how we can move loops over individual elements from Python to some of the highly optimized NumPy or SciPy extension functions.

However, the speed comes at a price. Using NumPy arrays, we no longer have the incredible flexibility of Python lists, which can hold basically anything. NumPy arrays always have only one datatype.
>>> a = np.array([1,2,3])
>>> a.dtype
dtype(‘int64’)
If we try to use elements of different types, NumPy will do its best to coerce them to the most reasonable common datatype:
>>> np.array([1, “stringy”])
array([‘1’, ‘stringy’], dtype=’|S8′)
>>> np.array([1, “stringy”, set([1,2,3])])
array([1, stringy, set([1, 2, 3])], dtype=object)

Introduction to NumPy, SciPy, and Matplotlib

Before we can talk about concrete machine learning algorithms, we have to talk about how best to store the data we will chew through. This is important as the most advanced learning algorithm will not be of any help to us if they will never finish. This may be simply because accessing the data is too slow. Or maybe its
representation forces the operating system to swap all day. Add to this that Python is an interpreted language (a highly optimized one, though) that is slow for many numerically heavy algorithms compared to C or Fortran. So we might ask why on earth so many scientists and companies are betting their fortune on Python even in the highly computation-intensive areas? The answer is that in Python, it is very easy to offload number-crunching tasks to the lower layer in the form of a C or Fortran extension.

That is exactly what NumPy and SciPy do (http://scipy.org/install.html). In this tandem, NumPy provides the support of highly optimized multidimensional arrays, which are the basic data structure of most state-of-the-art algorithms. SciPy uses those arrays to provide a set of fast numerical recipes. Finally, Matplotlib (http://matplotlib.org/) is probably the most convenient and feature-rich library to plot high-quality graphs using Python.

Installing Python Luckily, for all the major operating systems, namely Windows, Mac, and Linux,
there are targeted installers for NumPy, SciPy, and Matplotlib. If you are unsure about the installation process, you might want to install Enthought Python Distribution (
https://www.enthought.com/products/epd_free.php) or Python(x,y) (http://code.google.com/p/pythonxy/wiki/Downloads), which
come with all the earlier mentioned packages included.
Chewing data effciently with NumPy and
intelligently with SciPy
Let us quickly walk through some basic NumPy examples and then take a look at
what SciPy provides on top of it. On the way, we will get our feet wet with plotting using the marvelous Matplotlib package.

You will find more interesting examples of what NumPy can offer at

http://www.scipy.org/Tentative_NumPy_Tutorial. You will also fnd the book NumPy Beginner’s Guide – Second Edition, Ivan Idris,Packt Publishing very valuable.

Additional tutorial style guides are at http://scipy-lectures.github.com;

you may also visit the offcial SciPy tutorial at
http://docs.scipy.org/doc/scipy/reference/tutorial.

What you will Learn

This Blog will give you a broad overview of the types of learning algorithms that
are currently used in the diverse fields of machine learning and what to watch out
for when applying them. From our own experience, however, we know that doing
the “cool” stuff—using and tweaking machine learning algorithms such as
support
vector machines
(SVM), nearest neighbor search (NNS), or ensembles thereof—will
only consume a tiny fraction of the overall time of a good machine learning expert.
Looking at the following typical workflow, we see that most of our time will be spent
in rather mundane tasks:
1. Reading the data and cleaning it.
2. Exploring and understanding the input data.
3. Analyzing how best to present the data to the learning algorithm.
4. Choosing the right model and learning algorithm.
5. Measuring the performance correctly.
When talking about exploring and understanding the input data, we will need a
bit of statistics and basic math. But while doing this, you will see that those topics,
which seemed so dry in your math class, can actually be really exciting when you
use them to look at interesting data.
The journey begins when you read in the data. When you have to face issues such as
invalid or missing values, you will see that this is more an art than a precise science.
And a very rewarding one, as doing this part right will open your data to more
machine learning algorithms, and thus increase the likelihood of success.
With the data being ready in your program’s data structures, you will want to get a
real feeling of what kind of animal you are working with. Do you have enough data
to answer your questions? If not, you might want to think about additional ways to
get more of it. Do you maybe even have too much data? Then you probably want to
think about how best to extract a sample of it.Often you will not feed the data directly into your machine learning algorithm.Instead, you will find that you can refine parts of the data before training. Many
times, the machine learning algorithm will reward you with increased performance.You will even find that a simple algorithm with refined data generally outperforms a very sophisticated algorithm with raw data. This part of the machine learning workflow is called
feature engineering, and it is generally a very exciting and
rewarding challenge. Creative and intelligent that you are, you will immediately see the results.


Choosing the right learning algorithm is not simply a shootout of the three or four that are in your toolbox (there will be more algorithms in your toolbox that you will see). It is more of a thoughtful process of weighing different performance and functional requirements. Do you need fast results and are willing to sacrifice quality? Or would you rather spend more time to get the best possible result? Do you have a
clear idea of the future data or should you be a bit more conservative on that side? Finally, measuring the performance is the part where most mistakes are waiting for the aspiring ML learner. There are easy ones, such as testing your approach with the  same data on which you have trained. But there are more difficult ones; for example, when you have imbalanced training data. Again, data is the part that determines
whether your undertaking will fail or succeed.

We see that only the fourth point is dealing with the fancy algorithms. Nevertheless,we hope that this book will convince you that the other four tasks are not simply chores, but can be equally important if not more exciting. Our hope is that by the end of the book you will have truly fallen in love with data instead of learned algorithms.To that end, we will not overwhelm you with the theoretical aspects of the diverse ML
algorithms, as there are already excellent books in that area (you will fnd pointers in
Appendix, Where to Learn More about Machine Learning). Instead, we will try to provide an intuition of the underlying approaches in the individual chapters—just enough for you to get the idea and be able to undertake your first steps. Hence, this book is by no means “the definitive guide” to machine learning. It is more a kind of starter kit. We hope that it ignites your curiosity enough to keep you eager in trying to learn more
and more about this interesting field.

In the rest of this chapter, we will set up and get to know the basic Python libraries,NumPy and SciPy, and then train our first machine learning using scikit-learn. During this endeavor, we will introduce basic ML concepts that will later be used throughout the book. The rest of the chapters will then go into more detail through the five steps described earlier, highlighting different aspects of machine learning in Python using
diverse application scenarios.

Machine learning and Python

Machine learning (ML)  teaches machines how to carry out tasks by themselves.It is that simple. The complexity comes with the details, and that is most likely the
reason you are reading this Machine learning and Python blog Series.
Maybe you have too much data and too little insight, and you hoped that using
machine learning algorithms will help you solve this challenge. So you started to
dig into random algorithms. But after some time you were puzzled: which of the
myriad of algorithms should you actually choose?
Or maybe you are broadly interested in machine learning and have been reading
a few blogs and articles about it for some time. Everything seemed to be magic and
cool, so you started your exploration and fed some toy data into a decision tree or
a support vector machine. But after you successfully applied it to some other data,
you wondered, was the whole setting right? Did you get the optimal results? And
how do you know there are no better algorithms? Or whether your data was “the
right one”?
Welcome to the club! We, the authors, were at those stages once upon a time,
looking for information that tells the real story behind the theoretical textbooks
on machine learning. It turned out that much of that information was “black art”,
not usually taught in standard textbooks. So, in a sense, we wrote this book to our
younger selves; a book that not only gives a quick introduction to machine learning,
but also teaches you lessons that we have learned along the way. We hope that it
will also give you, the reader, a smoother entry into one of the most exciting fields
in Computer Science.