Python for AI & Data Analytics MCQs for NSCT
Python for AI & Data Analytics is the third topic in the NSCT's AI, Machine Learning & Data Analytics area. It tests whether you can read and predict short code using the four standard libraries: NumPy for arrays, pandas for tables, Matplotlib for plots and scikit-learn for models. The whole area carries 10% of the test, according to HEC's Areas of Competencies.
Expect "what does this code print?" questions. They count as application or analysis items, the two tiers where 2026 candidates scored 45.1% and 44.8% in the HEC NSCT report. Every code output below was run on NumPy 2.5 and pandas 3.0.
NumPy
NumPy's ndarray is an n-dimensional array that holds one data type (dtype) in contiguous memory. Operations run in compiled C loops, which is called vectorisation, so they are far faster than Python loops over lists.
import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a * 10) # [[10 20] [30 40]] element-wise
print(a.mean(axis=1)) # [1.5 3.5] one value per row
print(a + np.array([100, 200])) # [[101 202] [103 204]] broadcasting
The axis you pass is the one that disappears: axis=0 gives one result per column, axis=1 one per row. Broadcasting stretches dimensions of size 1 so that shapes such as (2, 2) and (2,) can be combined.
Exam angle: basic slices such as a[1:3] are views, so writing to them changes the original. Boolean and integer-array indexing return copies.
Pandas
pandas adds labelled data. A Series is a one-dimensional labelled array; a DataFrame is a table of Series that share a row index.
import pandas as pd
df = pd.DataFrame({"name": ["Ali", "Sara", "Omar", "Hina"],
"city": ["Lahore", "Karachi", "Lahore", "Multan"],
"marks": [72, None, 85, 64]})
print(df["marks"].isnull().sum()) # 1
print(df[df["marks"] > 70]["name"].tolist()) # ['Ali', 'Omar']
print(df.groupby("city")["marks"].mean().to_dict())
The last line prints {'Karachi': nan, 'Lahore': 78.5, 'Multan': 64.0}: Karachi's only mark is missing, so its group mean is NaN.
| Task | Method |
|---|---|
| Select by label | df.loc[row_label, "col"] |
| Select by position | df.iloc[0, 2] |
| Find missing values | df.isnull() or df.isna() |
| Drop or fill missing | df.dropna(), df.fillna(value) |
| Group and aggregate | df.groupby("key")["col"].mean() |
| Combine tables | df.merge(other, on="key", how="inner") |
Exam angle: pandas skips NaN in mean() and sum() by default, and aligns Series on their index labels before arithmetic, filling unmatched labels with NaN.
Matplotlib
Matplotlib draws charts. The quick pyplot style calls plt.plot(x, y) and plt.show(); the object-oriented style starts with fig, ax = plt.subplots() and then calls ax.plot(), ax.set_xlabel() and so on.
| Chart | Call | Shows |
|---|---|---|
| Line | plt.plot(x, y) | Trend over an ordered variable such as time |
| Scatter | plt.scatter(x, y) | Relationship between two numeric variables |
| Histogram | plt.hist(x, bins=10) | Distribution of one numeric variable |
| Bar | plt.bar(labels, values) | Comparison across categories |
Exam angle: match the chart to the question asked. "Distribution of marks" means histogram, "relationship between study hours and marks" means scatter.
Scikit-learn
scikit-learn gives every model the same interface. Estimators have fit(X, y) to learn and predict(X) to infer. Transformers such as StandardScaler have fit(), transform() and fit_transform(). X must be 2-D with shape (n_samples, n_features); one feature stored as a 1-D array needs x.reshape(-1, 1).
A typical flow: split with train_test_split (the default test share is 0.25), fit the scaler on the training set only, transform both sets with it, fit the model and score it on the test set. A Pipeline bundles these steps so the scaler can never see test rows.
Exam angle: fitting a scaler or imputer on the full dataset before splitting is data leakage, and the reported score will be optimistic.
Common traps
- Confusing a * b (element-wise) with a @ b or np.dot(a, b) (matrix or dot product).
- Expecting b = a to copy an array. It only adds a second name; use a.copy().
- Mixing up loc and iloc when the index is not 0, 1, 2 and so on.
- Testing for missing values with == np.nan. NaN never equals anything, including itself; use isna().
- Forgetting that a NumPy array keeps its dtype: putting 2.7 into an integer array stores 2.
- Passing a 1-D array to predict() when the model expects (n_samples, n_features).
Worked examples
1. Understanding. Which pandas object would you use to hold a table of student names, cities and marks? Answer: a DataFrame. Its columns can have different types, while a NumPy array would force one dtype on everything.
2. Application. What does np.array([[1, 2, 3], [4, 5, 6]])[:, 1] return?
Answer: [2 5]. The colon takes every row and 1 takes the second column, giving one value from each row.
3. Analysis. A Series is created as s = pd.Series([5, 6, 7], index=[1, 2, 3]). A student expects s.loc[1] and s.iloc[1] to be equal. What do they return?
Answer: 5 and 6. loc looks up the label 1, which is the first element, while iloc uses position 1, which is the second element. They only agree when the index is the default 0, 1, 2.
Practise
The quiz below has 100 questions on this topic, which you can filter by tier and difficulty.
Practise: 100 questions
FAQs
Do I need to memorise NumPy and pandas function names for the NSCT?
You need to recognise the common ones and predict what they do: array creation (array, arange, linspace, reshape), axis-based sums and means, Boolean filtering, loc and iloc, isnull, dropna, fillna, groupby and merge. You do not need rarely used arguments. Practising short outputs, as in the quiz below, is the fastest way to make them familiar.
What is the difference between a NumPy array and a pandas DataFrame?
A NumPy array is a block of numbers of one dtype, indexed only by position, and it is the fastest choice for maths. A DataFrame is a labelled table: rows have an index, columns have names and each column can have its own type. pandas is built on NumPy, and df.to_numpy() converts a DataFrame back to an array.
Why does scikit-learn need a 2-D array for X?
Each row of X is one sample and each column one feature, so X always has shape (n_samples, n_features), even with a single feature or a single sample. A 1-D array is ambiguous: it could be one sample with many features or many samples with one feature. Use reshape(-1, 1) for one feature or reshape(1, -1) for one sample.
Is Matplotlib still used when libraries such as seaborn exist?
Yes. Seaborn and the pandas plot() method are built on top of Matplotlib, so understanding figures, axes and the basic chart types helps with all of them. For the NSCT, focus on picking the right chart for a question and knowing that plt.subplots() returns a figure and axes.
Next step
Continue with Data Collection & Pre-processing MCQs, the next official topic, where these pandas skills are put to work on missing values and scaling. Revise Mathematical Foundations if the matrix questions slowed you down, or return to the AI and ML MCQs hub. Then try an NSCT mock test.