0% found this document useful (0 votes)
2 views12 pages

Full Code Explanation Guide

Code explanation for Data analysis
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

Full Code Explanation Guide

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

Social Media Analysis — Full Code & Explanation Guide

FULL CODE & EXPLANATION GUIDE


Social Media Impact on Life
Every line of code explained in plain English
Questions 10 – 18 · Python & Pandas

SECTION 1 — Setup: importing libraries and loading data


These are the very first lines of code in your notebook. They must run before anything else. Without
them, nothing works.

Step 1 — Import the libraries


import numpy as np
import pandas as pd

What this does:


import means 'bring this tool into our project so we can use it.'

numpy (nicknamed np) is a library for working with numbers and mathematical operations. We import
it because pandas relies on it internally.

pandas (nicknamed pd) is the main library for data analysis in Python. It lets us load, filter, group, and
calculate things from our dataset. Think of it like a very powerful version of Excel that we control with
code.

The 'as np' and 'as pd' parts give these libraries short nicknames so we don't have to type the full
name every time.

Step 2 — Load the Excel file


Social_media_impact = pd.read_excel('Social_media_impact_on_life.xlsx')

What this does:


pd.read_excel() is a pandas function that opens an Excel file and converts it into a DataFrame —
which is basically a table in Python, with rows and columns, just like a spreadsheet.

The result is stored in a variable called Social_media_impact. From this point on, whenever we write
Social_media_impact in our code, Python knows we are talking about this table of 1,705 students.

The file must be in the same folder as the notebook for this to work.

Step 3 — Check the shape of the data


Social_media_impact.shape

What this does:

Page 1
Social Media Analysis — Full Code & Explanation Guide

.shape tells us how big the dataset is. It returns two numbers: (rows, columns).

Our result is (1705, 11) — meaning 1,705 students and 11 columns of information per student.

This is always a good first step to confirm the data loaded correctly.

Step 4 — Preview the first few rows


Social_media_impact.head()

What this does:


.head() shows the first 5 rows of the dataset so we can see what the data looks like — what the
column names are, what kind of values they contain, and whether everything looks correct.

You can write .head(10) to see the first 10 rows instead.

SECTION 2 — Creating the age_group column


This is one of the most important parts of your notebook. You wrote a custom function and applied it to
the entire dataset to create a brand new column.

Step 1 — Define the age_group function


def age_group(age):
if age > 0 and age <= 20:
return('Teenager')
elif age > 20 and age <= 23:
return('Youth')
elif age > 23 and age < 26:
return('Adult')
else:
return('invalid age')

What this does:


def means 'define a function' — we are creating a reusable block of code that takes one input called
age and returns a category label.

The function works like a set of rules:


- If age is 20 or below → label them 'Teenager'
- If age is between 21 and 23 → label them 'Youth'
- If age is between 24 and 25 → label them 'Adult'
- Anything else → 'invalid age' (a safety net)

return means 'send this value back as the result.' The function does not print anything — it just gives
back a word.

Step 2 — Apply the function to every row


Social_media_impact['age_group'] = Social_media_impact['Age'].apply(age_group)

What this does:


Social_media_impact['Age'] selects just the Age column from our table.

Page 2
Social Media Analysis — Full Code & Explanation Guide

.apply(age_group) runs the age_group function on every single value in that column — all 1,705 ages
— one by one, and collects all the results.

Social_media_impact['age_group'] = ... creates a brand new column called age_group and fills it with
the results. This column did not exist before — we are adding it ourselves.

Think of it like dragging a formula down in Excel, except Python does it for all 1,705 rows automatically
in one line.

SECTION 3 — Question 10: Country with most positive overall


impact

country_pos_impact = Social_media_impact[Social_media_impact['Overall_Impact']
== 'Positive'] \
.groupby('Country')['Overall_Impact'].count() \
.reset_index() \
.sort_values('Overall_Impact', ascending=False)

country_pos_impact

Line-by-line explanation:
LINE 1 — Social_media_impact[Social_media_impact['Overall_Impact'] == 'Positive']
This is called filtering. The square brackets [ ] act like a sieve.
Social_media_impact['Overall_Impact'] == 'Positive' checks every row and returns True if the
Overall_Impact is 'Positive', False if not.
Wrapping this inside the outer [ ] keeps ONLY the rows where the condition is True.
Result: a smaller table containing only students who reported a Positive impact.

LINE 2 — .groupby('Country')['Overall_Impact'].count()
groupby('Country') splits the filtered data into groups — one group per country.
['Overall_Impact'] selects that column within each group.
.count() counts how many rows exist in each country group.
Result: a list of countries with the number of students who had a Positive impact.

LINE 3 — .reset_index()
After groupby, the country names become the 'index' (row labels) rather than a regular column.
reset_index() converts them back into a normal column so the table is clean and easy to read.

LINE 4 — .sort_values('Overall_Impact', ascending=False)


Sorts the table from highest count to lowest so the country with the most Positive students appears
first.
ascending=False means biggest number first (descending order).

ANSWER: India = 26 students (top named country). Denmark and Switzerland also 27 each.

SECTION 4 — Question 11: Age group to mental health score


by platform
Page 3
Social Media Analysis — Full Code & Explanation Guide

age_group_to_mental_P = Social_media_impact \
.groupby(['age_group', 'Most_Used_Platform'])['Mental_Health_Score'] \
.mean() \
.reset_index() \
.sort_values(['age_group', 'Mental_Health_Score'], ascending=[True,
False])

age_group_to_mental_P

Line-by-line explanation:
LINE 1 — .groupby(['age_group', 'Most_Used_Platform'])
This groups the data by TWO columns at the same time — age_group and Most_Used_Platform.
Every unique combination gets its own group. For example: (Teenager, TikTok) is one group, (Adult,
LinkedIn) is another group, and so on.
There are 3 age groups × 12 platforms = up to 36 possible combinations.

LINE 2 — ['Mental_Health_Score'].mean()
Selects the Mental_Health_Score column inside each group.
.mean() calculates the average mental health score for all students in that group.
So for the group (Teenager, TikTok), it adds up all mental health scores of teenage TikTok users and
divides by how many there are.

LINE 3 — .reset_index()
Makes the result into a clean flat table again.

LINE 4 — .sort_values(['age_group', 'Mental_Health_Score'], ascending=[True, False])


Sorts first by age_group alphabetically (Adult → Teenager → Youth), then within each group sorts by
mental health score from highest to lowest.
This makes it easy to see which platform is best and worst for each age group.

ANSWER: LinkedIn has the highest avg mental health scores for Adults (6.94) and Youth (6.87).
Facebook is highest for Teenagers (6.35). WhatsApp is consistently the lowest across all groups.

SECTION 5 — Question 12: Country with most users per


platform

# Step 1 — Get all platform counts by country


country_M_platform = Social_media_impact \
.groupby(['Country', 'Most_Used_Platform'])['Student_ID'] \
.count() \
.reset_index() \
.sort_values('Student_ID', ascending=False)

# Step 2 — Filter for each specific platform


for platform in ['Facebook', 'LinkedIn', 'Instagram', 'Snapchat']:
result = country_M_platform[
country_M_platform['Most_Used_Platform'] == platform
].head(1)
print(platform, ':', result[['Country', 'Student_ID']].values)

Line-by-line explanation:

Page 4
Social Media Analysis — Full Code & Explanation Guide

LINE 1-5 — Building the country-platform count table


.groupby(['Country', 'Most_Used_Platform']) groups by country AND platform at the same time.
['Student_ID'].count() counts how many students are in each country-platform combination.
.sort_values('Student_ID', ascending=False) puts the largest groups at the top.

LINE 6-10 — Looping through the 4 platforms


for platform in [...] is a loop — it repeats the block of code inside for each platform in the list.
On the first loop, platform = 'Facebook'. On the second, platform = 'LinkedIn', and so on.

country_M_platform[country_M_platform['Most_Used_Platform'] == platform]
This filters the table to only show rows for that specific platform.
.head(1) takes only the first row — which is the country with the highest count because we already
sorted.

ANSWER: Facebook → India (25), LinkedIn → USA (13), Instagram → USA (29), Snapchat → India
(14).

SECTION 6 — Question 13: Platform with most effect on


academic performance

# Correct approach (fixed from original notebook)


Plat_Acad_Perf = Social_media_impact[
Social_media_impact['Affects_Academic_Performance'] == 'Yes'
] \
.groupby('Most_Used_Platform')['Affects_Academic_Performance'] \
.count() \
.reset_index() \
.sort_values('Affects_Academic_Performance', ascending=False)

Plat_Acad_Perf

Line-by-line explanation:
LINE 1-3 — Filtering to only 'Yes' responses
Social_media_impact['Affects_Academic_Performance'] == 'Yes' checks every row.
The outer [ ] keeps only rows where a student said Yes, social media affects their academic
performance.
This immediately removes all students who said No, so we only analyse those who are affected.

LINE 4-5 — Grouping by platform and counting


.groupby('Most_Used_Platform') groups the filtered rows by which platform the student uses.
.count() counts how many 'Yes' students belong to each platform group.

LINE 6 — Sorting
.sort_values(..., ascending=False) puts the platform with the most affected students first.

IMPORTANT — Why the original code was wrong:


The original notebook used .max() instead of .count().
.max() on a column of 'Yes' and 'No' text always returns 'Yes' for every single group — because
alphabetically 'Yes' > 'No'.
This told us nothing useful. Using .count() after filtering to 'Yes' gives us the actual counts we need.

ANSWER: Instagram = 244, TikTok = 226, Facebook = 114, LinkedIn = 76 (lowest of main platforms).

Page 5
Social Media Analysis — Full Code & Explanation Guide

SECTION 7 — Question 14: Platform with most positive


impact

platform_pos_impact = Social_media_impact[
Social_media_impact['Overall_Impact'] == 'Positive'
] \
.groupby('Most_Used_Platform')['Overall_Impact'] \
.count() \
.reset_index() \
.sort_values('Overall_Impact', ascending=False)

platform_pos_impact

Line-by-line explanation:
LINE 1-3 — Filter to only Positive rows
Social_media_impact['Overall_Impact'] == 'Positive' returns True for every student who reported a
Positive overall impact.
The outer [ ] keeps only those rows — this is the same filtering technique used in Q10 and Q13.

LINE 4-5 — Group by platform and count


.groupby('Most_Used_Platform') divides the filtered positive students into groups, one per platform.
.count() counts how many positive-impact students are in each platform group.

LINE 6-7 — Sort and display


.sort_values('Overall_Impact', ascending=False) ranks from most to least positive.

The pattern across Q13 and Q14 — Filtering by a category ('Positive', 'Yes', 'Negative') and then
groupby + count — is the most repeated technique in this whole project. Once you understand it for
one question, you understand it for all of them.

ANSWER: Instagram = 121 positive students, Facebook = 109, LinkedIn = 65.


Interesting contradiction: Instagram is BOTH the most academically disruptive (Q13) AND the most
positively impactful (Q14).

SECTION 8 — Question 15: Sleep hours by overall impact

# Summary version — average sleep per impact group


sleep_H_to_Overall_impact = Social_media_impact \
.groupby('Overall_Impact')['Sleep_Hours_Per_Night'] \
.mean() \
.reset_index() \
.sort_values('Sleep_Hours_Per_Night', ascending=False)

sleep_H_to_Overall_impact

Line-by-line explanation:
LINE 1 — .groupby('Overall_Impact')
This splits the dataset into three groups based on the Overall_Impact column:

Page 6
Social Media Analysis — Full Code & Explanation Guide

- Group 1: all students with Positive impact


- Group 2: all students with Neutral impact
- Group 3: all students with Negative impact

LINE 2 — ['Sleep_Hours_Per_Night'].mean()
Inside each of the three groups, this selects the Sleep_Hours_Per_Night column and calculates the
average.
So we get one average sleep number for Positive students, one for Neutral, one for Negative.

LINE 3 — .reset_index()
Cleans up the index so Overall_Impact becomes a regular column again.

LINE 4 — .sort_values('Sleep_Hours_Per_Night', ascending=False)


Puts the group with the most sleep at the top.

ANSWER: Positive impact students → 7.90 hrs avg sleep.


Neutral impact students → 6.80 hrs avg sleep.
Negative impact students → 5.85 hrs avg sleep.
The difference between Positive and Negative is almost exactly 2 full hours per night. This is the
clearest trend in the entire project.

SECTION 9 — Question 16: Platform by average daily usage

plat_avg_daily_usage = Social_media_impact \
.groupby('Most_Used_Platform')['Avg_Daily_Usage_Hours'] \
.mean() \
.reset_index() \
.sort_values('Avg_Daily_Usage_Hours', ascending=False)

plat_avg_daily_usage

Line-by-line explanation:
LINE 1 — .groupby('Most_Used_Platform')
Splits all 1,705 students into 12 groups — one group for each social media platform.
Every student goes into exactly one group based on which platform they use most.

LINE 2 — ['Avg_Daily_Usage_Hours'].mean()
Within each platform group, this selects the Avg_Daily_Usage_Hours column.
.mean() adds up all the hours for every student in the group and divides by the number of students to
get the average.
For example: all WhatsApp users' daily hours are averaged into one single number.

LINE 3 — .reset_index()
Cleans up the result into a neat table.

LINE 4 — .sort_values('Avg_Daily_Usage_Hours', ascending=False)


Ranks platforms from most to least time-consuming.

ANSWER: WhatsApp = 6.48 hrs/day (highest), Snapchat = 5.37, TikTok = 5.34.


LINE = 3.25 hrs/day (lowest), LinkedIn = 4.67 hrs/day (second lowest).
Surprising finding: WhatsApp users spend more time daily than TikTok or Instagram users.

Page 7
Social Media Analysis — Full Code & Explanation Guide

SECTION 10 — Question 17: Gender that uses social media


most

# Overall gender totals


Gender_by_Plat = Social_media_impact \
.groupby('Gender')['Most_Used_Platform'] \
.count() \
.reset_index()

Gender_by_Plat

# Breakdown by gender AND platform


gender_platform_detail = Social_media_impact \
.groupby(['Gender', 'Most_Used_Platform'])['Student_ID'] \
.count() \
.reset_index() \
.sort_values('Student_ID', ascending=False)

gender_platform_detail

Line-by-line explanation:
PART 1 — Overall gender totals
.groupby('Gender') splits students into two groups: Male and Female.
['Most_Used_Platform'].count() counts how many students are in each gender group.
This gives us the total number of male vs female social media users in the dataset.

PART 2 — Breakdown by gender AND platform


.groupby(['Gender', 'Most_Used_Platform']) groups by BOTH columns simultaneously.
This creates up to 24 groups (2 genders × 12 platforms).
['Student_ID'].count() counts the number of students in each group.
.sort_values('Student_ID', ascending=False) shows the biggest groups first.

This two-step approach is very useful in data analysis — first look at the total, then look at the detail.
The total alone hides interesting patterns.

ANSWER: Overall — Male = 878, Female = 827 (males slightly higher).


But Female students dominate Instagram (236 F vs 153 M) and TikTok (154 F vs 141 M).
Male students dominate Facebook (164 M vs 92 F) and LinkedIn (97 M vs 63 F).

SECTION 11 — Question 18: Most used platform in China +


mental health

# Step 1 — Filter to only Chinese students


China = Social_media_impact[Social_media_impact['Country'] == 'China']

# Step 2 — Find the most used platform in China


Most_used_Plat_China = China \
.groupby('Most_Used_Platform')['Student_ID'] \

Page 8
Social Media Analysis — Full Code & Explanation Guide

.count() \
.reset_index() \
.sort_values('Student_ID', ascending=False)

Most_used_Plat_China

# Step 3 — Average mental health score for that platform's users


Avg_Mental_WeChat = Social_media_impact[
Social_media_impact['Most_Used_Platform'] == 'WeChat'
]['Mental_Health_Score'].mean()

print('Average mental health score for WeChat users:',


round(Avg_Mental_WeChat, 2))

Line-by-line explanation:
STEP 1 — China = Social_media_impact[Social_media_impact['Country'] == 'China']
This is row filtering again — the same technique from Q10 and Q13.
Social_media_impact['Country'] == 'China' creates a True/False check for every row.
The outer [ ] keeps only the rows where Country is exactly 'China'.
Result: a new smaller table called China containing only the 16 Chinese students in the dataset.

STEP 2 — .groupby('Most_Used_Platform')['Student_ID'].count()
Working only with the China table, we group by platform and count students.
This tells us how many Chinese students use each platform.
.sort_values(..., ascending=False) puts the most used platform at the top.

STEP 3 — Calculating the average mental health score


Social_media_impact[Social_media_impact['Most_Used_Platform'] == 'WeChat']
→ filters the FULL dataset (not just China) to all students who use WeChat.
['Mental_Health_Score'].mean()
→ calculates the average mental health score across all WeChat users globally.
round(..., 2) rounds the result to 2 decimal places for a clean display.

ANSWER: WeChat is #1 in China — 15 out of 16 Chinese students use it.


Average mental health score for WeChat users globally = 6.47 out of 10.
WeChat dominates in China because it is a super app — used for messaging, payments, news, and
social networking all in one.

SECTION 12 — Core concepts cheat sheet


These are the 6 fundamental tools used throughout the entire project. Understand these and you can
explain every line of code.

1. Filtering with [ ]
df[df['ColumnName'] == 'Value']
Keeps only the rows where a condition is True. Think of it as a filter or a sieve.
Use it when you want to focus on a specific group — e.g. only Chinese students, only Instagram
users, only Positive impact rows.

2. groupby()
[Link]('Column')['OtherColumn'].mean()

Page 9
Social Media Analysis — Full Code & Explanation Guide

[Link](['Col1', 'Col2'])['OtherColumn'].count()
Splits the data into groups based on a column, then applies a calculation to each group.
You can group by one column or multiple columns at once.
Common calculations: .count() to count rows, .mean() to average numbers, .sum() to add
numbers, .max()/.min() for extremes.

3. reset_index()
[Link]('Column')['Col2'].count().reset_index()
After groupby(), the grouped column becomes the index (row label), not a regular column.
reset_index() moves it back into the table as a normal column. Always add this after groupby to get a
clean readable table.

4. sort_values()
df.sort_values('Column', ascending=False) # highest first
df.sort_values('Column', ascending=True) # lowest first
Sorts the entire table by one or more columns.
ascending=False = biggest number first (descending).
ascending=True = smallest number first (ascending).
Used to rank results so the most important finding appears at the top.

5. value_counts()
df['ColumnName'].value_counts()
Counts how many times each unique value appears in a column.
Useful for text/category columns like gender, platform, country.
Automatically sorts from most common to least common.
Difference from count(): value_counts() works on one column and counts categories. .count() is used
after groupby() to count rows per group.

6. apply() with a custom function


def my_function(value):
if value > 10:
return 'High'
else:
return 'Low'

df['new_column'] = df['existing_column'].apply(my_function)
apply() runs a function on every single value in a column — one row at a time.
Whatever the function returns becomes the value in a new column.
Used in this project to convert raw Age numbers into age group labels (Teenager, Youth, Adult).

SECTION 13 — What to say when showing code in your


presentation
Use these sentence templates when you show any piece of code on screen. They make you sound
confident and knowledgeable.

Page 10
Social Media Analysis — Full Code & Explanation Guide

When showing a filter:


df[df['Column'] == 'Value']
Say: "Here I am filtering the dataset to keep only the rows where [column name] equals [value]. This
gives us a smaller focused table of just [group name]."

When showing groupby + mean:


[Link]('Column')['NumberCol'].mean()
Say: "Here I am grouping the data by [column] and calculating the average [column] for each group.
This lets us compare the numbers across different categories."

When showing groupby + count:


[Link]('Column')['Col2'].count()
Say: "Here I am grouping by [column] and counting how many students fall into each group. This tells
us which group is the largest."

When showing apply():


df['new_col'] = df['existing_col'].apply(my_function)
Say: "Here I am applying my custom function to every row of the Age column. It runs the function 1,705
times — once per student — and stores all the results in a new column called age_group."

When showing sort_values():


df.sort_values('Column', ascending=False)
Say: "I sorted the results from highest to lowest so the most important finding appears at the top of the
table."

SECTION 14 — Final answers summary table


Quick reference for all 9 question answers from the real data.

Q# Question Answer

Q10 Most positive country India (26), Denmark & Switzerland (27 each)

Q11 Age group & mental health by LinkedIn best for Adults (6.94) & Youth (6.87). Facebook
platform best for Teens (6.35). WhatsApp lowest.

Q12 Country per platform Facebook→India (25), LinkedIn→USA (13),


Instagram→USA (29), Snapchat→India (14)

Q13 Most academic effect Instagram (244 students), TikTok (226), Facebook (114)

Q14 Most positive platform Instagram (121), Facebook (109), LinkedIn (65)

Q15 Sleep vs impact Positive=7.90 hrs, Neutral=6.80 hrs, Negative=5.85 hrs

Q16 Most daily usage WhatsApp 6.48 hrs, Snapchat 5.37, TikTok 5.34,

Page 11
Social Media Analysis — Full Code & Explanation Guide

LinkedIn 4.67 (lowest)

Q17 Gender & social media Males overall: 878 vs 827 females. Females lead
Instagram & TikTok. Males lead Facebook.

Q18 China platform & mental health WeChat #1 (15/16 students). Avg mental health score of
WeChat users = 6.47/10

Page 12

You might also like