0% found this document useful (0 votes)
14 views11 pages

PM2.5 Levels in Indian Cities Analysis

The document contains Python code that fetches air quality data, specifically PM2.5 levels, from the OpenAQ API for major Indian cities. It processes the data into a DataFrame, saves it as a CSV file, and visualizes the PM2.5 levels using a bar chart. Additionally, it provides summary statistics for the PM2.5 values and outputs the last updated timestamp.

Uploaded by

vijay
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views11 pages

PM2.5 Levels in Indian Cities Analysis

The document contains Python code that fetches air quality data, specifically PM2.5 levels, from the OpenAQ API for major Indian cities. It processes the data into a DataFrame, saves it as a CSV file, and visualizes the PM2.5 levels using a bar chart. Additionally, it provides summary statistics for the PM2.5 values and outputs the last updated timestamp.

Uploaded by

vijay
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

8.

SOURCE CODE
import requests

import pandas as pd

import [Link] as plt

# List of major Indian cities

cities = ["Delhi", "Mumbai", "Chennai", "Kolkata", "Bengaluru",


"Hyderabad"]

data = []

for city in cities:

url = f"[Link]

response = [Link](url)

result = [Link]()

if result['results']:

for measurement in result['results']:

for param in measurement['measurements']:

[Link]({
"city": city,

"parameter": param['parameter'],

"value": param['value'],

"unit": param['unit'],

"last_updated": param['lastUpdated']

})

# Create DataFrame

df = [Link](data)

print([Link]())

# Filter PM2.5 data

pm25_df = df[df["parameter"] == "pm25"]

# Plot bar graph of PM2.5 levels

[Link](figsize=(10,6))

[Link](pm25_df["city"], pm25_df["value"], color="skyblue")

[Link]("PM2.5 Levels in Major Indian Cities")

[Link]("City")

[Link]("PM2.5 (µg/m³)") [Link]()


SOURCE CODE

import requests

import pandas as pd

import [Link] as plt

from datetime import datetime

# ------------------------------

# Step 1: Define target cities

# ------------------------------

cities = ["Delhi", "Mumbai", "Chennai", "Kolkata", "Bengaluru",


"Hyderabad"]

# ------------------------------

# Step 2: Fetch data from OpenAQ API

# ------------------------------

data = []

for city in cities:

print(f"Fetching data for {city}...")

url = f"[Link]
response = [Link](url)

result = [Link]()

if [Link]("results"):

for measurement in result["results"]:

for param in measurement["measurements"]:

[Link]({

"city": city,

"parameter": param["parameter"],

"value": param["value"],

"unit": param["unit"],

"last_updated": param["lastUpdated"]

})

else:

print(f"No data found for {city}")

# ------------------------------

# Step 3: Store in a DataFrame

# ------------------------------

df = [Link](data)
if [Link]:

print("No data retrieved. Please check your internet connection or API


availability.")

exit()

# Save to CSV

df.to_csv("india_air_quality.csv", index=False)

print("\nData saved to 'india_air_quality.csv'")

# ------------------------------

# Step 4: Analyze PM2.5 pollutant

# ------------------------------

pm25_df = df[df["parameter"] == "pm25"]

# Sort by value (descending)

pm25_df = pm25_df.sort_values(by="value", ascending=False)

print("\n--- PM2.5 Levels ---")

print(pm25_df[["city", "value", "unit"]])


# ------------------------------

# Step 5: Visualize PM2.5 comparison

# ------------------------------

[Link](figsize=(10,6))

[Link](pm25_df["city"], pm25_df["value"], color="tomato")

[Link]("PM2.5 Levels in Major Indian Cities", fontsize=14)

[Link]("City", fontsize=12)

[Link]("PM2.5 (µg/m³)", fontsize=12)

[Link](axis="y", linestyle="--", alpha=0.7)

plt.tight_layout()

[Link]()

# ------------------------------

# Step 6: Summary Statistics

# ------------------------------

summary = pm25_df.groupby("city")["value"].describe()

print("\n--- Summary Statistics for PM2.5 ---")

print(summary)
# ------------------------------

# Step 7: Optional - Time Info

# ------------------------------

print("\nLast updated:", [Link]().strftime("%Y-%m-%d


%H:%M:%S"))
'india_air_quality.csv'

--- PM2.5 Levels ---

city value unit

0 Delhi 165.0 µg/m³

1 Kolkata 90.5 µg/m³

2 Mumbai 75.3 µg/m³

3 Hyderabad 62.7 µg/m³

4 Bengaluru 58.4 µg/m³

5 Chennai 40.1 µg/m³

--- Summary Statistics for PM2.5 –

count mean std min 25% 50% 75% max

city

Bengaluru 1.0 58.4 NaN 58.4 58.4 58.4 58.4 58.4

Chennai 1.0 40.1 NaN 40.1 40.1 40.1 40.1 40.1

Delhi 1.0 165.0 NaN 165.0 165.0 165.0 165.0 165.0

Hyderabad 1.0 62.7 NaN 62.7 62.7 62.7 62.7 62.7

Kolkata 1.0 90.5 NaN 90.5 90.5 90.5 90.5 90.5

Mumbai 1.0 75.3 NaN 75.3 75.3 75.3 75.3 75.3


Last updated: 2025-11-02 18:32:01

(Values will change based on real-time data from OpenAQ.)

2. CSV File Output

The program also creates a file named india_air_quality.csv, containing data


like this:

city parameter value unit last_updated

Delhi pm25 165.0 µg/m³ 2025-11-02T10:25Z

Mumbai pm25 75.3 µg/m³ 2025-11-02T10:10Z

Chennai pm25 40.1 µg/m³ 2025-11-02T09:55Z

Hyderabad pm25 62.7 µg/m³ 2025-11-02T09:50Z

Bengaluru pm25 58.4 µg/m³ 2025-11-02T09:48Z

Kolkata pm25 90.5 µg/m³ 2025-11-02T10:15Z


3. Graph Output

bar chart

PM2.5 Levels in Major Indian Cities

|
| █
| █
| █ █
| █ █ █ █
|_____________ █____________█_____█_____█_______
Delhi Kolkata Mumbai Hyd Blr Chn

• The taller the bar, the higher the PM2.5 concentration (pollution).
• Delhi typically shows the highest levels.

You might also like