0% found this document useful (0 votes)
10 views6 pages

DataFrame Operations and Analysis Guide

The document contains a Jupyter Notebook with various data manipulation and analysis techniques using pandas and numpy. It includes operations like renaming columns, filtering data, handling missing values, merging DataFrames, and visualizing data through pie charts and bar graphs. Additionally, it covers Monte Carlo simulations for estimating coefficients in regression analysis.

Uploaded by

Aimen
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)
10 views6 pages

DataFrame Operations and Analysis Guide

The document contains a Jupyter Notebook with various data manipulation and analysis techniques using pandas and numpy. It includes operations like renaming columns, filtering data, handling missing values, merging DataFrames, and visualizing data through pie charts and bar graphs. Additionally, it covers Monte Carlo simulations for estimating coefficients in regression analysis.

Uploaded by

Aimen
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

12/19/25, 4:44 PM Jupyter Notebook — generated with runcell

In [ ]: df = [Link](columns={"OldName": "NewName"})
# Rename one column
[Link] = [Link]().[Link](" ", "_")
# Remove spaces from column names (avoids KeyError)
df_2020 = df[df["Year"] == 2020]
# Keep only rows where Year = 2020
df[df["GDP_Trillion_USD"] > 5]
# Filter rows where GDP > 5

df["GDP_Trillion_USD"].isnull().sum()
# Count missing values in a column
df["GDP_Trillion_USD"] = df["GDP_Trillion_USD"].fillna(
df["GDP_Trillion_USD"].mean()
)
# Fill missing values with column mean
df["GDP_Trillion_USD"] = [Link]("Country_Code")
["GDP_Trillion_USD"].transform(
lambda x: [Link]([Link]())
)
# Fill missing GDP using mean GDP of each country

merged = [Link](
df1,
df2,
on="Country_Code",
how="left" or how=inner
)
# Left join: keep all rows from df1
combined = [Link]([df_2019, df_2020], axis=0)
# Stack two DataFrames row-wise

df.drop_duplicates()
# Remove duplicate rows

about:blank 1/6
12/19/25, 4:44 PM Jupyter Notebook — generated with runcell

In [ ]: Groupby
[Link]("Region")["GDP_Trillion_USD"].sum()
# Total GDP per region
df.sort_values(by="GDP_Trillion_USD", ascending=False)
# Sort GDP from highest to lowest
[Link][df["GDP_Trillion_USD"].idxmax()]
# Row with highest GDP
df.to_csv("[Link]", index=False)
# Save DataFrame to CSV file

#Descriptive Stats
can_read = (data_all['s2aq01'] =='yes')
read_pct = can_read.mean()*100

print(' Percentage of Individuals who can read:', read_pct)

#Visualisations
province_counts= data_all['province'].value_counts()
[Link](figsize=(6,6))
[Link](province_counts, autopct='%1.1f%%')

[Link]("pie chart_pdf")

#Lit rate by povince- Bar graph


literacy = (
(data_bothyears["s2aq01"].astype(str).[Link]() == "yes") |
(data_bothyears["s2aq02"].astype(str).[Link]() == "yes")
)
lit_by_province = [Link](data_bothyears["province"]).mean() * 100
[Link](lit_by_province.index, lit_by_province.values)
[Link]("Literacy Rate (%)")
[Link]("Literacy Rate by Province")
[Link](0, 100)
[Link](rotation=45)
[Link]()

#Boxplot
hours_worked = data_bothyears["s1bq02"].dropna()
[Link](hours_worked, vert= True)
[Link]()

about:blank 2/6
12/19/25, 4:44 PM Jupyter Notebook — generated with runcell

In [ ]: #Single dummy
df["female"] = (df["sex"] == "female").astype(int)
#Multiple dummies
dummies = pd.get_dummies(df["province"], drop_first=True)
df = [Link]([df, dummies], axis=1)

df["class1"] = (df["pclass"] == 1).astype(int)


df["class2"] = (df["pclass"] == 2).astype(int)
# class 3 is base group

Y = df["survived"]
X = df[["female", "class1", "class2"]]

about:blank 3/6
12/19/25, 4:44 PM Jupyter Notebook — generated with runcell

In [ ]: #NUMPY
import numpy as np
[Link](28768)
n = 10000
# a) Ones column
ones = [Link](n)
# b) Education (Uniform 0–18)
education = [Link](0, 18, n)
# c) Experience (Normal =3, =1.7)
experience = [Link](3, 1.7, n)
# d) Gender (Binomial p=0.46 → Female=1)
female = [Link](1, 0.46, n)
# Combine into X matrix
X = np.column_stack((ones, education, experience, female))
# Show mean and SD of variables
means = [Link](axis=0)
stds = [Link](axis=0)
print("Means:", means)
print("Standard Deviations:", stds)

To choose 500 samples from 10,000 obs


# Step 1: Assume you already have population data (10,000 obs)
# For demonstration, let’s simulate it:
[Link](42)
n_population = 10000
education = [Link](12, 2, n_population) # avg 12 years of␣
↪education
experience = [Link](10, 4, n_population) # avg 10 years of␣
↪experience
female = [Link](0, 2, n_population) # 0 = male, 1 = female
hourly_wage = 5 + 0.8*education + 0.5*experience - 2*female + [Link].
↪randn(n_population)
# Combine into a DataFrame (optional for visualization)
population = [Link]({
'education': education,
'experience': experience,
'female': female,
'hourly_wage': hourly_wage
})
# Step 2: Draw random sample of 500 observations (without replacement)
sample_ids = [Link](n_population, size=500, replace=False)
sample = [Link][sample_ids]
# Step 3: Define dependent (y) and independent (X) variables
y = sample['hourly_wage'].values
2
X = np.column_stack([
[Link](500),
sample['education'].values,
sample['experience'].values,
sample['female'].values
])
# Step 4: Print mean of each sample variable
print("Means of Sample Variables:")

about:blank 4/6
12/19/25, 4:44 PM Jupyter Notebook — generated with runcell
print(f"Education: {sample['education'].mean():.2f}")
print(f"Experience: {sample['experience'].mean():.2f}")
print(f"Female: {sample['female'].mean():.2f}")
print(f"Hourly wage:{sample['hourly_wage'].mean():.2f}")

Montecarlo simulation

In [ ]: import numpy as np
import pandas as pd
[Link](42) # for reproducibility
beta_true = [Link]([1, 0.8, -0.6, 2]) # population (4 coefficients)
n = 500 # sample size per iteration
iterations = 100 # total simulations
k = len(beta_true) # number of coefficients (4)
# Storage matrix for all ̂estimates
beta_store = [Link]((iterations, k))
# Step 1: Repeat 100 iterations
for i in range(iterations):
# (a) Generate X (constant + 3 random regressors)
X = np.column_stack([[Link](n), [Link](n, k-1)])
# (b) Generate y = X +
e = [Link](n) # random error term
y = X @ beta_true + e
# (c) Estimate ̂= (X'X)^(-1) X'y
beta_hat = [Link](X.T @ X) @ (X.T @ y)
# (d) Store ̂in matrix
beta_store[i, :] = beta_hat
# Step 2: Compute mean of each estimated coefficient
beta_mean = beta_store.mean(axis=0)
print("Population : ", [Link](beta_true, 3))
print("Mean of estimated ̂over 100 simulations:")
print([Link](beta_mean, 3))
#Part 3 :
# Calculate running averages
running_avg = [Link](beta_store, axis=0) / [Link](1, iterations + 1).
↪reshape(-1, 1)
4
# Show the last few (to illustrate convergence)
print("Running averages at last 5 iterations:")
print([Link](running_avg[-5:], 4))
# Show final running average (iteration 100)
print("\nFinal running average (iteration 100):")
print([Link](running_avg[-1], 4))

about:blank 5/6
12/19/25, 4:44 PM Jupyter Notebook — generated with runcell

Exported with runcell — convert notebooks to HTML or PDF anytime at [Link].

about:blank 6/6

Common questions

Powered by AI

The 'drop_duplicates' method removes duplicate rows based on all columns, which can be problematic if some distinct columns are erroneously considered duplicates, or if unique rows have duplicated subsets. This approach might lead to loss of useful information if mistakenly removed. To mitigate this, specify the subset parameter with the columns that determine duplicates to ensure only relevant duplicates are considered. Alternatively, perform a careful inspection with conditional logic before removal .

Performing a groupby operation involves first specifying the column to group by, in this case, 'Region'. Follow this with the aggregation function needed, such as sum, to aggregate GDP data. This operation can be done using df.groupby('Region')['GDP_Trillion_USD'].sum(). Aggregating by region allows for the analysis of economic trends and resources allocation at a regional rather than national level, highlighting disparities or growth patterns that might inform policy and economic decisions .

A boxplot can be created using plt.boxplot(), where you input the variable to be visualized, such as 'hours_worked'. It displays the median, quartiles, and any outliers within the data set. Interpretation involves identifying central tendency, variability, and potential outliers. Insights include understanding the typical working hours, detecting skewness, and identifying anomalies, which could indicate non-standard work schedules or inconsistent data practices .

Stacking two DataFrames row-wise using pd.concat() combines datasets vertically, appending one DataFrame's rows to another's. This is significant for combining datasets from multiple time frames, like df_2019 and df_2020, ensuring data continuity over periods or when concatenating different datasets by observation. It is essential in scenarios requiring comprehensive analysis over time or aggregating complete datasets that share schema but differ structurally or temporally .

A simulated population is created using np.random to generate uniform, normal, or binomial distributions for respective data attributes: education, experience, and gender. This includes specifying parameters like mean and standard deviation for these distributions. Limitations of this approach include potential misrepresentations of real-world variability if distributions or parameter values don't closely match reality, leading to biased or unrealistic simulation outputs. Moreover, simulated data might lack real-world complexity and context .

Monte Carlo simulations provide a robust way to estimate the distribution of regression coefficients by simulating the sampling process multiple times over defined iterations. This method captures variability and uncertainty, offering insights into how estimates might vary in repeated samples. The reliability of results improves as it accounts for randomness and error indirectly through simulation. However, it depends heavily on how well the simulation parameters approximate the real-world data conditions. Inaccuracies in assumption or skewed parameters might result in biased reliability evaluations .

A left join retains all rows from the left DataFrame and adds matching rows from the right DataFrame, filling in with NaN where there is no match, using 'pd.merge()' with how='left'. In contrast, an inner join keeps only rows with matching keys in both DataFrames. A left join is preferred when ensuring that all data from the primary dataset (left DataFrame) is preserved in the merged result, essential in scenarios where the primary dataset's integrity and completeness is crucial .

Missing GDP values can be filled using the column mean or the mean GDP of each country. The method involves grouping the dataset by 'Country_Code' and applying a fillna function that computes the mean of each group, effectively leveraging local information. This approach ensures that missing data is filled in a manner that is coherent with the related group, thus maintaining the statistical properties of the dataset .

Dummy variables are created to transform categorical variables into a numerical format that can be utilized in regression and other statistical models, particularly those requiring numerical input. Creating dummies provides a binary flag for each category level, except one, which acts as a baseline. This impacts analysis by allowing categorical data to contribute interpretatively to model estimates, enabling differentiation in categorical impacts while avoiding multicollinearity via the elimination of one level as base .

The percentage of individuals who can read is calculated by taking the boolean column 's2aq01' denoting 'yes' as 1, then calculating its mean using .mean() function and multiplying by 100. Interpretation involves understanding this percentage as a direct measure of literacy, indicating the proportion of the sample population that is literate, thus reflecting educational or socio-development factors in the analyzed demographic .

You might also like