PANDAS DATAFRAME QUESTIONS

PROGRAM 1: Sales Performance Analysis (DataFrame: SALES)

PROGRAM 1) Given a DataFrame SALES containing quarterly sales (in thousands) of 6 electronic items with item codes as indexes:

 .      Item      Q1   Q2 Q3 Q4
I101  Laptop    450  520 480 600
I102  Mobile    820  790850 910
I103  Tablet    310   340  290  360
I104  Monitor   220  250 240 280
I105  Printer   180   190  210   200
I106  Scanner   140   160 150 170

Write Python code for the following:
a) Create the above DataFrame SALES.
b) Display the shape, size, and column names of the DataFrame using DataFrame attributes.
c) Increase the Q4 sales of all items by 10 percent.
d) Add a new column ‘Total_Sales’ storing the sum of Q1, Q2, Q3, and Q4 for each item.
e) Display the details of items whose Q1 sales are greater than 300.
f) Display ‘Item’ and ‘Q4’ sales for item codes I102, I104, and I106 using loc.
g) Rename the column ‘Q1’ to ‘Quarter1’ and ‘Q2’ to ‘Quarter2’.
h) Delete the row with index ‘I106’ permanently from the DataFrame.
i) Plot a multi-bar chart comparing Quarter1 and Q4 sales of all remaining items with proper labels, title, and legend.
j) Plot a horizontal bar chart (barh) showing the ‘Total_Sales’ of each item in green color.


ANSWERS:-


#PROGRAM-1
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#a) Create the above DataFrame SALES.
data = {‘Item’: [‘Laptop’, ‘Mobile’, ‘Tablet’, ‘Monitor’, ‘Printer’,’Scanner’],
        ‘Q1’:[ 450, 820, 310, 220,180,140],
        ‘Q2’:[520,790 ,340, 250,190,160 ],
        ‘Q3’:[480,850 ,290 ,240 ,210 ,150],
        ‘Q4’:[ 600, 910, 360, 280, 200, 170]}
idx = [‘I101’, ‘I102’, ‘I103’, ‘I104’, ‘I105’, ‘I106’]
SALES = pd.DataFrame(data, index=idx)
print(“DataFrame SALES:”)
print(SALES)

#b) Display the shape, size, and column names of the DataFrame using DataFrame attributes.
print(“\nShape:”, SALES.shape)
print(“Size:”, SALES.size)
print(“Columns:”, SALES.columns)

#c) Increase the Q4 sales of all items by 10 percent.
SALES[‘Q4’] = SALES[‘Q4’] + (SALES[‘Q4’] * 0.10)
print(“\nAfter 10% increase in Q4:”)
print(SALES)

#d) Add a new column ‘Total_Sales’ storing the sum of Q1, Q2, Q3, and Q4 for each item.
SALES[‘Total_Sales’] = SALES[‘Q1’] + SALES[‘Q2’] + SALES[‘Q3’] + SALES[‘Q4’]
print(“\nAfter adding Total_Sales:”,SALES)

#e) Display the details of items whose Q1 sales are greater than 300.
print(“\nItems with Q1 sales > 300:”)
print(SALES[SALES[‘Q1’] > 300])

#f) Display ‘Item’ and ‘Q4’ sales for item codes I102, I104, and I106 using loc.
print(“\nItem and Q4 sales for I102, I104, I106:”)
print(SALES.loc[[‘I102’, ‘I104’, ‘I106’], [‘Item’, ‘Q4’]])

#g) Rename the column ‘Q1’ to ‘Quarter1’ and ‘Q2’ to ‘Quarter2’.
SALES.rename(columns={‘Q1’: ‘Quarter1’, ‘Q2’: ‘Quarter2’}, inplace=True)
print(“\nAfter renaming columns:”)
print(SALES)

#h) Delete the row with index ‘I106’ permanently from the DataFrame.
SALES.drop(‘I106’, axis=0, inplace=True)
print(“\nAfter deleting row I106:”)
print(SALES)

#i) Plot a multi-bar chart comparing Quarter1 and Q4 sales of all remaining items.
x = np.arange(len(SALES))
plt.bar(x – 0.15, SALES[‘Quarter1′], width=0.3, color=’blue’, label=’Quarter 1′)
plt.bar(x + 0.15, SALES[‘Q4′], width=0.3, color=’orange’, label=’Quarter 4′)
plt.xticks(x, SALES[‘Item’])
plt.xlabel(‘Electronic Items’)
plt.ylabel(‘Sales (in Thousands)’)
plt.title(‘Quarter 1 vs Quarter 4 Sales Comparison’)
plt.legend()
plt.show()

#j) Plot a horizontal bar chart (barh) showing the ‘Total_Sales’ of each item in green color.
plt.barh(SALES[‘Item’], SALES[‘Total_Sales’], color=’green’)
plt.xlabel(‘Total Sales (in Thousands)’)
plt.ylabel(‘Electronic Items’)
plt.title(‘Total Annual Sales per Item’)
plt.show()

PROGRAM 2) Given a DataFrame WEATHER recording maximum and minimum temperatures (in Celsius) and rainfall (in mm) across 6 cities:

 .CityMaxTemp    MinTemp    Rainfall
C01Delhi      42         28         120
C02Mumbai     34         26         850
C03Chennai    38         27         420
C04    Kolkata    36         25         610
C05 Shimla     24        12         310
C06 Jaipur     44        29         95

Write Python code for the following:
a) Create the above DataFrame WEATHER with C01 to C06 as index.
b) Display the index labels, data types of each column, and transpose of the DataFrame.
c) Add a new column ‘Temp_Diff’ representing the difference between MaxTemp and MinTemp.
d) Display all records where Rainfall is greater than 400 mm.
e) Change the MaxTemp of ‘Shimla’ (C05) from 24 to 26 using loc.
f) Display the City and Rainfall of alternate cities starting from C01 using iloc.
g) Add a new row for city ‘Lucknow’ with index ‘C07’ and values [‘Lucknow’, 41, 27, 210, 14].
h) Drop the ‘MinTemp’ column from the DataFrame.
i) Plot a line chart comparing MaxTemp and Rainfall across all cities using different markers and line styles.
j) Plot a bar chart for ‘Temp_Diff’ against ‘City’ with custom xticks, ylabel, and title.


SOLUTION 2: Weather & Temperature Monitoring (WEATHER)
ANSWER:
#PROGRAM-2
import pandas as pd
import matplotlib.pyplot as plt

#a) Create the above DataFrame WEATHER with C01 to C06 as index.
data = {'City': ['Delhi', 'Mumbai', 'Chennai', 'Kolkata', 'Shimla', 'Jaipur'],
        'MaxTemp':,
        'MinTemp':,
        'Rainfall':}
idx = ['C01', 'C02', 'C03', 'C04', 'C05', 'C06']
WEATHER = pd.DataFrame(data, index=idx)
print("DataFrame WEATHER:")
print(WEATHER)

#b) Display the index labels, data types of each column, and transpose of the DataFrame.
print("\nIndex Labels:", WEATHER.index)
print("\nData Types:\n", WEATHER.dtypes)
print("\nTranspose of WEATHER:\n", WEATHER.T)

#c) Add a new column 'Temp_Diff' representing the difference between MaxTemp and MinTemp.
WEATHER['Temp_Diff'] = WEATHER['MaxTemp'] - WEATHER['MinTemp']
print("\nAfter adding Temp_Diff:")
print(WEATHER)

#d) Display all records where Rainfall is greater than 400 mm.
print("\nCities with Rainfall > 400 mm:")
print(WEATHER[WEATHER['Rainfall'] > 400])

#e) Change the MaxTemp of 'Shimla' (C05) from 24 to 26 using loc.
WEATHER.loc['C05', 'MaxTemp'] = 26
WEATHER.loc['C05', 'Temp_Diff'] = WEATHER.loc['C05', 'MaxTemp'] - WEATHER.loc['C05', 'MinTemp']
print("\nAfter updating Shimla MaxTemp:")
print(WEATHER)

#f) Display the City and Rainfall of alternate cities starting from C01 using iloc.
print("\nCity and Rainfall of alternate cities:")
print(WEATHER.iloc[0::2, [0, 3]])

#g) Add a new row for city 'Lucknow' with index 'C07' and values ['Lucknow', 41, 27, 210, 14].
WEATHER.loc['C07'] = ['Lucknow', 41, 27, 210, 14]
print("\nAfter adding Lucknow (C07):")
print(WEATHER)

#h) Drop the 'MinTemp' column from the DataFrame.
WEATHER.drop('MinTemp', axis=1, inplace=True)
print("\nAfter dropping MinTemp column:")
print(WEATHER)

#i) Plot a line chart comparing MaxTemp and Rainfall across all cities using different markers and line styles.
plt.plot(WEATHER['City'], WEATHER['MaxTemp'], color='red', marker='o', linestyle='-', label='Max Temp (C)')
plt.plot(WEATHER['City'], WEATHER['Rainfall'], color='blue', marker='s', linestyle='--', label='Rainfall (mm)')
plt.xlabel('Cities')
plt.ylabel('Values')
plt.title('Max Temperature vs Rainfall Across Cities')
plt.legend()
plt.show()

#j) Plot a bar chart for 'Temp_Diff' against 'City' with custom xticks, ylabel, and title.
plt.bar(WEATHER['City'], WEATHER['Temp_Diff'], color='purple')
plt.xticks(rotation=30)
plt.xlabel('City Name')
plt.ylabel('Temperature Difference (Celsius)')
plt.title('Diurnal Temperature Variation by City')
plt.show()

PROGRAM 3) Given a DataFrame HOSPITAL storing ward details, total beds, occupied beds, and daily charges (in Rs.):

Ward NameTotal BedsOccupiedCharge Per Day
W1General100851500
W2ICU30288500
W3Pediatric40322500
W4Maternity50413000
W5Cardiac25229000
W6Emergency35304000

Write Python code for the following:
a) Create the above DataFrame HOSPITAL.
b) Display the number of dimensions (ndim), axes, and check if the DataFrame is empty.
c) Compute and add a new column ‘Vacant_Beds‘ (Total_Beds – Occupied).
d) Compute and add a new column ‘Daily_Revenue‘ (Occupied * Charge_Per_Day).
e) Display records of wards where Vacant_Beds are less than 5.
f) Display Ward, Occupied, and Daily_Revenue of W2, W4, and W5 using loc.
g) Rename index ‘W1’ to ‘W01’ and ‘W6’ to ‘W06’.
h) Remove the ‘Total_Beds‘ column permanently using drop().
i) Plot a bar chart comparing ‘Occupied’ and ‘Vacant_Beds‘ for all wards side by side.
j) Plot a line chart of ‘Daily_Revenue‘ with red dashed line, circular markers, gridlines, and appropriate title.

<PRE><CODE>
ANSWER:
#PROGRAM-3
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#a) Create the above DataFrame HOSPITAL.
data = {'Ward': ['General', 'ICU', 'Pediatric', 'Maternity', 'Cardiac', 'Emergency'],
        'Total_Beds':,
        'Occupied':,
        'Charge_Per_Day':}
idx = ['W1', 'W2', 'W3', 'W4', 'W5', 'W6']
HOSPITAL = pd.DataFrame(data, index=idx)
print("DataFrame HOSPITAL:")
print(HOSPITAL)

#b) Display the number of dimensions (ndim), axes, and check if the DataFrame is empty.
print("\nDimensions (ndim):", HOSPITAL.ndim)
print("Axes:", HOSPITAL.axes)
print("Is Empty:", HOSPITAL.empty)

#c) Compute and add a new column 'Vacant_Beds' (Total_Beds - Occupied).
HOSPITAL['Vacant_Beds'] = HOSPITAL['Total_Beds'] - HOSPITAL['Occupied']

#d) Compute and add a new column 'Daily_Revenue' (Occupied * Charge_Per_Day).
HOSPITAL['Daily_Revenue'] = HOSPITAL['Occupied'] * HOSPITAL['Charge_Per_Day']
print("\nAfter adding Vacant_Beds and Daily_Revenue:")
print(HOSPITAL)

#e) Display records of wards where Vacant_Beds are less than 5.
print("\nWards with Vacant_Beds < 5:")
print(HOSPITAL[HOSPITAL['Vacant_Beds'] < 5])

#f) Display Ward, Occupied, and Daily_Revenue of W2, W4, and W5 using loc.
print("\nDetails of W2, W4, W5:")
print(HOSPITAL.loc[['W2', 'W4', 'W5'], ['Ward', 'Occupied', 'Daily_Revenue']])

#g) Rename index 'W1' to 'W01' and 'W6' to 'W06'.
HOSPITAL.rename(index={'W1': 'W01', 'W6': 'W06'}, inplace=True)
print("\nAfter renaming indexes:")
print(HOSPITAL)

#h) Remove the 'Total_Beds' column permanently using drop().
HOSPITAL.drop('Total_Beds', axis=1, inplace=True)
print("\nAfter dropping Total_Beds column:")
print(HOSPITAL)

#i) Plot a bar chart comparing 'Occupied' and 'Vacant_Beds' for all wards side by side.
x = np.arange(len(HOSPITAL))
plt.bar(x - 0.15, HOSPITAL['Occupied'], width=0.3, color='crimson', label='Occupied Beds')
plt.bar(x + 0.15, HOSPITAL['Vacant_Beds'], width=0.3, color='seagreen', label='Vacant Beds')
plt.xticks(x, HOSPITAL['Ward'])
plt.xlabel('Hospital Wards')
plt.ylabel('Number of Beds')
plt.title('Occupied vs Vacant Beds by Ward')
plt.legend()
plt.show()

#j) Plot a line chart of 'Daily_Revenue' with red dashed line, circular markers, gridlines, and appropriate title.
plt.plot(HOSPITAL['Ward'], HOSPITAL['Daily_Revenue'], color='red', linestyle='--', marker='o', label='Daily Revenue')
plt.xlabel('Hospital Wards')
plt.ylabel('Revenue (in Rs.)')
plt.title('Daily Revenue Generated per Ward')
plt.grid(True)
plt.legend()
plt.show()
</CODE></PRE>

PROGRAM 4) Given a DataFrame EMP containing employee details, department, basic salary, and experience (in years):

  .     EName     Dept      Basic     Exp
E10   Rohan     IT        65000     5
E20   Sneha     HR        48000     3
E30   Amit      Finance   72000     8
E40   Priya     IT        80000     9
E50   Karan     Sales     42000     2
E60   Neha      Finance   58000      4

Write Python code for the following:
a) Create the above DataFrame EMP .
b) Display the first 3 rows using head() and last 2 rows using tail().
c) Add a column ‘Bonus’ which is 15% of Basic salary for all employees.
d) Add a column ‘Net_Salary’ as the sum of Basic and Bonus.
e) Display details of employees working in the ‘IT’ department with Experience greater than 6 years.
f) Update the Basic salary of ‘Karan’ (E50) to 46000.
g) Display EName and Net_Salary of employees from E20 to E50 using loc.
h) Rename the column ‘Exp’ to ‘Experience’ and ‘Basic’ to ‘Basic_Pay’.
i) Plot a histogram of ‘Net_Salary’ with 4 bins, edge color black, and yellow fill color.
j) Plot a bar chart showing ‘EName’ vs ‘Net_Salary’ with customized y-axis limits using ylim().


ANSWER:
#PROGRAM-4
import pandas as pd
import matplotlib.pyplot as plt

#a) Create the above DataFrame EMP.
data = {‘EName’: [‘Rohan’, ‘Sneha’, ‘Amit’, ‘Priya’, ‘Karan’, ‘Neha’],
        ‘Dept’: [‘IT’, ‘HR’, ‘Finance’, ‘IT’, ‘Sales’, ‘Finance’],
        ‘Basic’:,
        ‘Exp’:}
idx = [‘E10’, ‘E20’, ‘E30’, ‘E40’, ‘E50’, ‘E60’]
EMP = pd.DataFrame(data, index=idx)
print(“DataFrame EMP:”)
print(EMP)

#b) Display the first 3 rows using head() and last 2 rows using tail().
print(“\nFirst 3 rows:”)
print(EMP.head(3))
print(“\nLast 2 rows:”)
print(EMP.tail(2))

#c) Add a column ‘Bonus’ which is 15% of Basic salary for all employees.
EMP[‘Bonus’] = EMP[‘Basic’] * 0.15

#d) Add a column ‘Net_Salary’ as the sum of Basic and Bonus.
EMP[‘Net_Salary’] = EMP[‘Basic’] + EMP[‘Bonus’]
print(“\nAfter adding Bonus and Net_Salary:”)
print(EMP)

#e) Display details of employees working in the ‘IT’ department with Experience greater than 6 years.
print(“\nIT Employees with Experience > 6 years:”)
print(EMP[(EMP[‘Dept’] == ‘IT’) & (EMP[‘Exp’] > 6)])

#f) Update the Basic salary of ‘Karan’ (E50) to 46000.
EMP.loc[‘E50’, ‘Basic’] = 46000
EMP.loc[‘E50’, ‘Bonus’] = EMP.loc[‘E50’, ‘Basic’] * 0.15
EMP.loc[‘E50’, ‘Net_Salary’] = EMP.loc[‘E50’, ‘Basic’] + EMP.loc[‘E50’, ‘Bonus’]
print(“\nAfter updating Karan’s Basic salary:”)
print(EMP)

#g) Display EName and Net_Salary of employees from E20 to E50 using loc.
print(“\nEName and Net_Salary from E20 to E50:”)
print(EMP.loc[‘E20′:’E50’, [‘EName’, ‘Net_Salary’]])

#h) Rename the column ‘Exp’ to ‘Experience’ and ‘Basic’ to ‘Basic_Pay’.
EMP.rename(columns={‘Exp’: ‘Experience’, ‘Basic’: ‘Basic_Pay’}, inplace=True)
print(“\nAfter renaming columns:”)
print(EMP)

#i) Plot a histogram of ‘Net_Salary’ with 4 bins, edge color black, and yellow fill color.
plt.hist(EMP[‘Net_Salary’], bins=4, edgecolor=’black’, color=’yellow’)
plt.xlabel(‘Net Salary Range’)
plt.ylabel(‘Number of Employees’)
plt.title(‘Distribution of Employee Net Salary’)
plt.show()

#j) Plot a bar chart showing ‘EName’ vs ‘Net_Salary’ with customized y-axis limits using ylim().
plt.bar(EMP[‘EName’], EMP[‘Net_Salary’], color=’teal’)
plt.ylim(40000, 100000)
plt.xlabel(‘Employee Name’)
plt.ylabel(‘Net Salary (in Rs.)’)
plt.title(‘Employee Net Salary Comparison’)
plt.show()

PROGRAM 5) Given a DataFrame MEDALS showing medals won by 6 houses in an annual sports meet:

ColorGoldSilverBronze
H1Red121510
H2Blue181214
H3Green101416
H4Yellow15119
H5Orange8912
H6Purple141611

Write Python code for the following:
a) Create the above DataFrame MEDALS.
b) Display the total number of rows and columns, and memory usage or info of the DataFrame.
c) Add a column ‘Total_Medals’ containing the sum of Gold, Silver, and Bronze medals for each house.
d) Add a column ‘Points’ calculated as: (Gold * 5) + (Silver * 3) + (Bronze * 1).
e) Display the House and Points of houses that won more than 12 Gold medals.
f) Subtract 2 from the Bronze medals of ‘Green’ house (H3) due to a rule penalty, and recalculate its Total_Medals.
g) Display the rows at index positions 1, 3, and 4 using iloc.
h) Delete the row ‘H5’ and column ‘Bronze’ from the DataFrame.
i) Plot a multi-line chart showing Gold and Silver medals for all remaining houses with distinct colors and legends.
j) Plot a bar chart comparing ‘Points’ of each house with different colors for each bar and a descriptive title.


ANSWER:
#PROGRAM-5
import pandas as pd
import matplotlib.pyplot as plt

#a) Create the above DataFrame MEDALS.
data = {‘House’: [‘Red’, ‘Blue’, ‘Green’, ‘Yellow’, ‘Orange’, ‘Purple’],
        ‘Gold’:,
        ‘Silver’:,
        ‘Bronze’:}
idx = [‘H1’, ‘H2’, ‘H3’, ‘H4’, ‘H5’, ‘H6’]
MEDALS = pd.DataFrame(data, index=idx)
print(“DataFrame MEDALS:”)
print(MEDALS)

#b) Display the total number of rows and columns, and info of the DataFrame.
print(“\nTotal Rows and Columns (shape):”, MEDALS.shape)
print(“\nDataFrame Info:”)
MEDALS.info()

#c) Add a column ‘Total_Medals’ containing the sum of Gold, Silver, and Bronze medals for each house.
MEDALS[‘Total_Medals’] = MEDALS[‘Gold’] + MEDALS[‘Silver’] + MEDALS[‘Bronze’]

#d) Add a column ‘Points’ calculated as: (Gold * 5) + (Silver * 3) + (Bronze * 1).
MEDALS[‘Points’] = (MEDALS[‘Gold’] * 5) + (MEDALS[‘Silver’] * 3) + (MEDALS[‘Bronze’] * 1)
print(“\nAfter adding Total_Medals and Points:”)
print(MEDALS)

#e) Display the House and Points of houses that won more than 12 Gold medals.
print(“\nHouses with more than 12 Gold medals:”)
print(MEDALS[MEDALS[‘Gold’] > 12][[‘House’, ‘Points’]])

#f) Subtract 2 from the Bronze medals of ‘Green’ house (H3) due to a rule penalty, and recalculate its Total_Medals.
MEDALS.loc[‘H3’, ‘Bronze’] = MEDALS.loc[‘H3’, ‘Bronze’] – 2
MEDALS.loc[‘H3’, ‘Total_Medals’] = MEDALS.loc[‘H3’, ‘Gold’] + MEDALS.loc[‘H3’, ‘Silver’] + MEDALS.loc[‘H3’, ‘Bronze’]
print(“\nAfter penalty on Green house (H3):”)
print(MEDALS)

#g) Display the rows at index positions 1, 3, and 4 using iloc.
print(“\nRows at index positions 1, 3, and 4:”)
print(MEDALS.iloc[[1, 3, 4]])

#h) Delete the row ‘H5’ and column ‘Bronze’ from the DataFrame.
MEDALS.drop(‘H5’, axis=0, inplace=True)
MEDALS.drop(‘Bronze’, axis=1, inplace=True)
print(“\nAfter deleting row H5 and column Bronze:”)
print(MEDALS)

#i) Plot a multi-line chart showing Gold and Silver medals for all remaining houses with distinct colors and legends.
plt.plot(MEDALS[‘House’], MEDALS[‘Gold’], color=’gold’, marker=’o’, linewidth=2, label=’Gold Medals’)
plt.plot(MEDALS[‘House’], MEDALS[‘Silver’], color=’silver’, marker=’s’, linewidth=2, label=’Silver Medals’)
plt.xlabel(‘House Name’)
plt.ylabel(‘Medal Count’)
plt.title(‘Gold vs Silver Medals Won by Houses’)
plt.legend()
plt.show()

#j) Plot a bar chart comparing ‘Points’ of each house with different colors for each bar and a descriptive title.
bar_colors = [‘red’, ‘blue’, ‘green’, ‘yellow’, ‘purple’]
plt.bar(MEDALS[‘House’], MEDALS[‘Points’], color=bar_colors, edgecolor=’black’)
plt.xlabel(‘House Name’)
plt.ylabel(‘Total Points’)
plt.title(‘Annual Sports Meet – House Points Tally’)
plt.show()

error: Content is protected !!
Scroll to Top