Series

The pandas series is a one-dimensional array. It can hold any data type. The labels are referred to as the index. Now, we are going to look at an example of series without declaring an index and series with declaring an index. First, we will look at an example of series without declaring an index. For that, create a script called  series_without_index.py and write the following content in it:

import pandas as pd
import numpy as np

s_data = pd.Series([10, 20, 30, 40], name = 'numbers')
print(s_data)

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 series_without_index.py

The output is as follows :

0 10
1 20
2 30
3 40
Name: numbers, dtype: int64

In the preceding example, we learned about series without declaring an index. First, we imported two modules: pandas and numpy. Next, we created the s_data object that will store the series data. In that series, we created a list and instead of declaring an index, we provided the name attribute, which will give a name to the list, and then we printed the data. In the output, the left column is your index for the data. Even if we never provide the index, pandas will give it implicitly. The index will always start from 0. Underneath the columns is the name of our series and the data type of the values.

Now, we are going to look at an example of a series when declaring an index. Here we are also going to perform indexing and slicing operations. For that, create a script called series_with_index.py and write the following content in it:

import pandas as pd
import numpy as np

s_data = pd.Series([10, 20, 30, 40], index = ['a', 'b', 'c', 'd'], name = 'numbers')
print(s_data)
print()
print("The data at index 2 is: ", s_data[2])
print("The data from range 1 to 3 are: ", s_data[1:3])

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 series_with_index.py
a 10
b 20
c 30
d 40
Name: numbers, dtype: int64


The data at index 2 is: 30
The data from range 1 to 3 are:
b 20
c 30
Name: numbers, dtype: int64

In the preceding example, we provided an index value for our data in the index attribute. In the output, the left column is the index values that we provided.

..................Content has been hidden....................

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