Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิเคราะห์ข้อมูลสำรวจประชากร (Census Data) ใน Python

ใช้ Python วิเคราะห์ข้อมูลสำรวจประชากรอินเดีย (India Census 2011) พร้อมการแสดงผลแบบ Heatmap และ Bar Chart

ข้อมูล

  • 640 แขวง (districts), 118 คอลัมน์
  • ประกอบด้วย: demographic, economic, housing, education, assets ฯลฯ

1. เปรียบเทียบความคล้ายคลึงระหว่าง 2 รัฐ (Similarity Matrix)

คำนวณ Euclidean distance ที่ normalize แล้วระหว่างแขวงของ Assam และ Andhra Pradesh แล้วแสดง Heatmap

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import math
from matplotlib.colors import Normalize

df = pd.read_csv('india-districts-census-2011.csv')
df_assam = df[df['State name'] == 'ASSAM']
df_ap = df[df['State name'] == 'ANDHRA PRADESH']

def similarity_matrix(df1, df2):
    matrix = []
    for _, r1 in df1.iterrows():
        row_scores = []
        for _, r2 in df2.iterrows():
            n = 0
            for c in df.columns[3:]:  # skip id cols
                max_c, min_c = df[c].max(), df[c].min()
                if max_c != min_c:
                    n += ((r1[c] - r2[c]) / (max_c - min_c)) ** 2
            row_scores.append(1 / math.sqrt(n) if n > 0 else 1)
        matrix.append(row_scores)
    return matrix

sim = similarity_matrix(df_assam, df_ap)

# หาคู่ที่คล้ายที่สุด
max_val, max_i, max_j = 0, 0, 0
for i, row in enumerate(sim):
    for j, val in enumerate(row):
        if val > max_val:
            max_val, max_i, max_j = val, i, j

print(f"Most similar: {df_assam.iloc[max_i]['District name']} (Assam) - {df_ap.iloc[max_j]['District name']} (AP)")

# Heatmap
norm = Normalize()
plt.figure(figsize=(20,20))
sns.heatmap(norm(sim), xticklabels=df_ap['District name'], 
            yticklabels=df_assam['District name'], cmap='Oranges')
plt.title("Similarity Matrix: Assam vs Andhra Pradesh")
plt.show()

2. เปรียบเทียบพารามิเตอร์เฉพาะ: Computer Penetration vs Cultivator Workers

Bar chart แนวนอนเปรียบเทียบจำนวนครัวเรือนมีคอมพิวเตอร์กับจำนวนเกษตรกรในแต่ละรัฐ

import numpy as np

grouped = df.groupby('State name')
states, comps, cults = [], [], []
for name, grp in grouped:
    states.append(name)
    comps.append(grp.iloc[:, 36].sum())   # Households with Computer
    cults.append(grp.iloc[:, 21].sum())   # Cultivator Workers

y_pos = np.arange(len(states))
width = 0.35
fig, ax = plt.subplots(figsize=(15,15))
ax.barh(y_pos, cults, width, label='Cultivator Workers', color='g')
ax.barh(y_pos + width, comps, width, label='Households with Computer', color='b')
ax.set_yticks(y_pos + width/2)
ax.set_yticklabels(states)
ax.set_xlabel('Population')
ax.set_title('Computer Penetration vs Cultivator Workers by State')
ax.legend()
plt.show()

สรุป

Python + pandas + matplotlib/seaborn เหมาะสำหรับ Exploratory Data Analysis ขนาดใหญ่