Python Data Manipulation with Pandas Questions
Skills and concepts for extracting, transforming, and preparing tabular and array data in Python using libraries such as pandas and NumPy. Candidates should be comfortable reading data from common formats, working with pandas DataFrame and Series objects, selecting and filtering rows and columns, boolean indexing and query methods, groupby aggregations, sorting, merging and joining dataframes, reshaping data with pivot and melt, handling missing values, and converting and validating data types. Understand NumPy arrays and vectorized operations for efficient numeric computation, when to prefer vectorized approaches over Python loops, and how to write readable, reusable data processing functions. At higher levels, expect questions on memory efficiency, profiling and optimizing slow pandas operations, processing data that does not fit in memory, and designing robust pipelines that handle edge cases and mixed data types.
Sample Answer
# pip install line_profiler
%load_ext line_profiler
%lprun -f process_fn process_fn(df)Sample Answer
import pandas as pd
from csv import Sniffer
raw = open('vendor.csv', 'r', encoding='utf-8', errors='replace').read(2048)
dialect = Sniffer().sniff(raw) # guesses delimiter/quotechar
df = pd.read_csv('vendor.csv', delimiter=dialect.delimiter,
quotechar=dialect.quotechar, engine='python', on_bad_lines='skip')Sample Answer
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import os
REQUIRED_COLUMNS = {'user_id', 'ts', 'amount'}
DTYPES = {'user_id': 'int64', 'amount': 'float64'}
def process_file(local_csv_path, out_dir, chunksize=100_000):
for i, chunk in enumerate(pd.read_csv(local_csv_path, chunksize=chunksize)):
# 1. validate schema before doing anything else
missing = REQUIRED_COLUMNS - set(chunk.columns)
if missing:
raise ValueError(f'missing required columns: {missing}')
# 2. normalize/transform: enforce types, quarantine clearly bad rows
chunk['ts'] = pd.to_datetime(chunk['ts'], utc=True, errors='coerce')
chunk['amount'] = pd.to_numeric(chunk['amount'], errors='coerce')
bad_rows = chunk['ts'].isna() | chunk['amount'].isna()
if bad_rows.any():
chunk.loc[bad_rows].to_csv(os.path.join(out_dir, 'quarantine.csv'), mode='a', index=False)
chunk = chunk[~bad_rows]
chunk = chunk.astype(DTYPES, errors='ignore')
# 3. write this chunk to a partition, atomically
for date, part in chunk.groupby(chunk['ts'].dt.date):
partition_dir = os.path.join(out_dir, f'date={date}')
os.makedirs(partition_dir, exist_ok=True)
final_path = os.path.join(partition_dir, f'part-{i}.parquet')
tmp_path = final_path + '.tmp'
pq.write_table(pa.Table.from_pandas(part, preserve_index=False), tmp_path)
os.replace(tmp_path, final_path) # atomic rename, no half-written filesSample Answer
import pandas as pd
def combine_fragments(fragment_iterable):
parts = []
for chunk in fragment_iterable:
parts.append(chunk) # O(1): just a list append, no DataFrame copy
result = pd.concat(parts, ignore_index=True) # ONE allocation for the final shape
return resultSample Answer
import pandas as pd
df = pd.DataFrame({"score": [50, 90, 30, 85, 40, 95, 20, 88]}) # index is 0..7 by default
passing = df[df["score"] >= 80]
print(passing)
# score
# 1 90
# 3 85
# 5 95
# 7 88
passing.loc[3] # works, but returns the row that was ALWAYS labeled 3 (score 85)
passing.loc[2] # KeyError: 2 -- label 2 (score 30) was filtered out entirelypassing.iloc[2] # 3rd row by position (label 5, score 95), whatever its label happens to bepassing = df[df["score"] >= 80].reset_index(drop=True)
passing.loc[1] # now label 1 == position 1, since the index was rebuilt as 0,1,2,...Unlock Full Question Bank
Get access to hundreds of Python Data Manipulation with Pandas interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.