Code Explanation:
Import Pandas
import pandas as pd
Loads the Pandas library, commonly used for working with data in tables or labeled arrays.
We use pd as an alias so we can type shorter commands.
Create a Pandas Series
s = pd.Series([10, 15, 20, 25, 30])
pd.Series() creates a one-dimensional labeled array.
This Series looks like:
index value
0 10
1 15
2 20
3 25
4 30
Apply a condition and modify values
s[s > 20] -= 5
s > 20 produces a boolean mask:
0 False
1 False
2 False
3 True
4 True
dtype: bool
s[s > 20] selects only the values where the mask is True:
→ [25, 30]
-= 5 subtracts 5 from each of those values in place:
25 → 20
30 → 25
Updated Series is now:
index value
0 10
1 15
2 20
3 20
4 25
Calculate the mean
print(s.mean())
s.mean() calculates the average:
(10 + 15 + 20 + 20 + 25) / 5 = 90 / 5 = 18.0
Output:
18.0
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment