How it works...

The simplest constructor for a Series object takes as argument a Python iterable, as shown in the first example, reproduced as follows:

series1 = pd.Series(['Alice', 'Bob', 'Joe', 'Mary'])
series1

The iterable must be one-dimensional, such as a plain list, a NumPy array, or a file object with a stream of data. The preceding code will create the following Series object:

0    Alice
1      Bob
2      Joe
3     Mary
dtype: object

The first column in the display is the index, which is a pandas object of type Index. The default index uses integers, starting at 0. Also notice that a Series object has a specific data type, represented by a NumPy dtype object. In this example, the data in the Series object consists of strings, so the dtype is object.

In the second example, shown as follows, we specify the index for the series explicitly:

series2 = pd.Series(['Honda', 'Honda', 'Honda', 'Toyota', 'Ford'],
index=['CR-V', 'Civic', 'Accord', 'Highlander', 'F-150'])
series2

The index is set by using the index option in the constructor, and accepts a one-dimensional Python iterable. The data created with this command is displayed as follows:

CR-V           Honda
Civic          Honda
Accord         Honda
Highlander    Toyota
F-150           Ford
dtype: object

In the final example, we use a dictionary to specify both the index and the data, as follows:

series3 = pd.Series({'a':102, 'b':np.NaN, 'c':303}, dtype=np.float64)
series3

The keys of the dictionary become the index, and the values become the corresponding data. The Series object constructed by this code is displayed as follows:

a    102.0
b      NaN
c    303.0
dtype: float64

There are two other features of notice demonstrated in this example:

  • The NumPy value NaN, which means not a number, is used to represent missing numerical data
  • We specify the data type explicitly with the dtype option in the constructor
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset