def top_k(query, matrix, k=3):
# matrix: (n_docs, dim), query: (dim,)
sims = (matrix @ query) / (np.linalg.norm(matrix, axis=1) * np.linalg.norm(query))
idx = np.argpartition(-sims, k)[:k] # O(n) selection
return idx[np.argsort(-sims[idx])] # sort only the k winnersQ62. What is the difference between a view and a copy in NumPy?
Basic slicing returns a view (shares memory, edits affect the original); fancy or boolean indexing returns a copy. Use .copy() when you need independence.
Q63. How do you handle missing data in Pandas?
import pandas as pd
df.isna().sum() # count missing per column
df = df.dropna(subset=["text"]) # drop rows missing text
df["score"] = df["score"].fillna(df["score"].median())Q64. groupby, merge, and apply: show each.
agg = df.groupby("model")["score"].agg(["mean", "std", "count"])
merged = results.merge(meta, on="doc_id", how="left")
df["n_words"] = df["text"].apply(lambda t: len(t.split())) # prefer df["text"].str.split().str.len()Q65. loc vs iloc?
loc selects by label (and boolean masks); iloc selects by integer position.
df.loc[df["score"] > 0.8, ["question", "score"]]
df.iloc[:5, :2]Q66. How do you read large CSV files efficiently?
for chunk in pd.read_csv("big.csv", chunksize=100_000, usecols=["id", "text"]):
process(chunk)Also set dtype to smaller types and use Parquet instead of CSV when possible.