Informatics Practices · Ch 2 — Data Handling using Pandas – I
Methods of Series
Methods of Series
Understanding Series Methods
A Pandas Series comes with built-in methods that let you quickly inspect, summarise, and manipulate your data. These methods save you from writing loops or manual slicing. The textbook introduces three essential methods using a sample Series created from np.arange(10, 20, 1), which holds the integers 10 through 19.
>>> seriesTenTwenty = pd.Series(np.arange(10, 20, 1))
>>> print(seriesTenTwenty)
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
dtype: int32
Each method is designed for a specific task — looking at the beginning, counting valid entries, or checking the end.
head(n) — First Few Members
The head() method returns the first n elements of the Series. If you do not pass any argument, it defaults to showing the first 5 entries. This is extremely useful when you have a large dataset and just want a quick peek at the top rows to confirm the data looks correct.
Example with argument:
>>> seriesTenTwenty.head(2)
0 10
1 11
dtype: int32
Here, only the first two values (10 and 11) are returned.
Example without argument (default behaviour):
>>> seriesTenTwenty.head()
0 10
1 11
2 12
3 13
4 14
dtype: int32
The first five values are displayed.
The default value of n is always 5. You can pass any positive integer to see that many rows from the start.
count() — Number of Non-NaN Values
The count() method returns the total number of non-NaN (i.e., non-missing) values in the Series. It ignores any NaN entries automatically. In our sample Series, all 10 values are present and valid, so it returns 10.
>>> seriesTenTwenty.count()
10
count() does not return the total length of the Series if there are missing values. It only counts the actual, non-null entries. If your data has blanks, count() will be less than len(series).
tail(n) — Last Few Members
The tail() method works exactly like head(), but from the opposite end — it returns the last n elements. Again, the default is 5 if no argument is given.
Example with argument:
>>> seriesTenTwenty.tail(2)
8 18
9 19
dtype: int32
The last two values (18 and 19) are shown.
Example without argument (default behaviour):
>>> seriesTenTwenty.tail()
5 15
6 16
7 17
8 18
9 19
dtype: int32
The last five values are displayed.
Use head() and tail() together to quickly check both ends of your data — this is a common first step in data cleaning to spot outliers or missing entries at the boundaries.
Quick Reference Table
| Method | Purpose | Default n | Example Output (with n=2) | …
| Method | Explanation | Example |
|---|---|---|
| head(n) | Returns the first n members of the series. If the value for n is not passed, then by default n takes 5 and the first five members are displayed. | >>> seriesTenTwenty.head(2) 0 10 1 11 dtype: int32 >>> seriesTenTwenty.head() 0 10 1 11 2 12 3 13 4 14 dtype: int32 |
| count() | Returns the number of non-NaN values in the Series | >>> seriesTenTwenty.count() 10 |