Series in Python with examples | Lecture 2
Here’s a
detailed explanation of Series in Python with examples:
What is a Series?
- A Series is a
one-dimensional labeled array in Python provided by the pandas
library.
- It can hold data of any type
(integers, floats, strings, Python objects, etc.).
- It is similar to a column in
a table or a one-dimensional array but with labels (indexes).
Key Characteristics
- Homogeneous: All elements in a Series
are of the same data type.
- Indexing: Each element in the Series
has a unique label (default: integers starting from 0).
- Mutability: Series is mutable; you can
change its values.
How to Create a Series?
- From a List
2. import pandas as pd
3.
4. data = [10, 20, 30, 40, 50]
5. series = pd.Series(data)
6. print(series)
Output:
0 10
1 20
2 30
3 40
4 50
dtype: int64
- With Custom Index
8. data = [100, 200, 300]
9. index = ['A', 'B', 'C']
10.series = pd.Series(data, index=index)
11.print(series)
Output:
A 100
B 200
C 300
dtype: int64
- From a Dictionary
13.data = {'x': 1, 'y': 2, 'z': 3}
14.series = pd.Series(data)
15.print(series)
Output:
x 1
y 2
z 3
dtype: int64
- From a Scalar Value
17.series = pd.Series(5, index=['a', 'b', 'c'])
18.print(series)
Output:
a 5
b 5
c 5
dtype: int64
Accessing Elements in a Series
- By Index Position
2. data = [10, 20, 30, 40]
3. series = pd.Series(data)
4. print(series[1])
# Output: 20
- By Index Label
6. data = {'a': 10, 'b': 20, 'c': 30}
7. series = pd.Series(data)
8. print(series['b'])
# Output: 20
- Slicing
10.print(series[0:2])
# Output: first two elements
Operations on Series
- Arithmetic Operations
2. s1 = pd.Series([1, 2, 3])
3. s2 = pd.Series([4, 5, 6])
4. print(s1 + s2)
Output:
0 5
1 7
2 9
dtype: int64
- Applying Functions
6. series = pd.Series([1, 2, 3, 4])
7. print(series.apply(lambda x: x**2))
Output:
0 1
1 4
2 9
3 16
dtype: int64
- Filtering
9. series = pd.Series([10, 20, 30, 40])
10.print(series[series > 25])
Output:
2 30
3 40
dtype: int64
Key Methods
|
Method |
Description |
Example |
|
head(n) |
First n elements |
series.head(2) |
|
tail(n) |
Last n elements |
series.tail(2) |
|
mean() |
Calculate
mean |
series.mean() |
|
sum() |
Sum of
elements |
series.sum() |
|
unique() |
Unique
values |
series.unique() |
|
value_counts() |
Frequency
of unique values |
series.value_counts() |
|
isnull()/notnull() |
Check
for missing values |
series.isnull() |
|
sort_values() |
Sort
values |
series.sort_values() |
Practical Example
Marks Analysis
data = {'Math': 90, 'Science': 85, 'English': 78}
marks = pd.Series(data)
print("Total Marks:", marks.sum())
print("Average Marks:", marks.mean())
print("Subjects with Marks > 80:")
print(marks[marks > 80])
Output:
Total Marks: 253
Average Marks: 84.33333333333333
Subjects with Marks > 80:
Math 90
Science 85
dtype: int64
This
gives you a comprehensive overview of Series in Python with examples. Let me
know if you'd like more clarification!
Comments
Post a Comment