0% found this document useful (0 votes)
9 views40 pages

Python Interview Questions

The document contains 100 Python interview questions and answers tailored for data analysts and data scientists. It covers a wide range of topics including string manipulation, data structures, and data analysis using libraries like pandas and NumPy. Each question is paired with a concise code-based answer, making it a practical resource for interview preparation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views40 pages

Python Interview Questions

The document contains 100 Python interview questions and answers tailored for data analysts and data scientists. It covers a wide range of topics including string manipulation, data structures, and data analysis using libraries like pandas and NumPy. Each question is paired with a concise code-based answer, making it a practical resource for interview preparation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

100 Python Interview Questions &

Answers for Data Analyst and


Data Science

1. Question: Reverse a string


Answer:
s = 'hello'
print(s[::-1])

2. Question: Check if a number is prime


Answer:
n=7
print(all(n % i != 0 for i in range(2,
int(n**0.5) + 1)))

3. Question: Find factorial using recursion

SONIYA KAUSHIK | in
Answer:
def fact(n):
return 1 if n == 0 else n * fact(n-1)
print(fact(5))

4. Question: Check palindrome string


Answer:
s = 'madam'
print(s == s[::-1])

5. Question: Find largest number in a list


Answer:
nums = [1, 5, 2]
print(max(nums))

6. Question: Swap two variables

SONIYA KAUSHIK | in
Answer:
a, b = 5, 10
a, b = b, a
print(a, b)

7. Question: Count vowels in a string


Answer:
s = 'hello'
print(sum(1 for ch in s if ch in 'aeiou'))

8. Question: Check Armstrong number


Answer:
n = 153
print(sum(int(d) ** 3 for d in str(n)) == n)

9. Question: Generate Fibonacci series

SONIYA KAUSHIK | in
Answer:
a, b = 0, 1
for _ in range(5):
print(a)
a, b = b, a + b

10. Question: Find GCD of two numbers


Answer:
import math
print([Link](12, 15))

11. Question: Check anagram


Answer:
s1, s2 = 'listen', 'silent'
print(sorted(s1) == sorted(s2))

SONIYA KAUSHIK | in
12. Question: Reverse words in a sentence
Answer:
s = 'hello world'
print(' '.join([Link]()[::-1]))

13. Question: Find duplicates in a list


Answer:
nums = [1, 2, 2, 3]
print([x for x in set(nums) if [Link](x)
> 1])

14. Question: Find second largest number in


a list
Answer:
nums = [1, 2, 3, 4]
print(sorted(set(nums))[-2])

SONIYA KAUSHIK | in
15. Question: Check if string contains only
digits
Answer:
print('123'.isdigit())

16. Question: Flatten nested list


Answer:
nested = [[1, 2], [3, 4]]
flat = [x for sub in nested for x in sub]
print(flat)

17. Question: Sort dictionary by values


Answer:
d = {'a': 2, 'b': 1}
print(dict(sorted([Link](), key=lambda x:
x[1])))

SONIYA KAUSHIK | in
18. Question: Count words in a string
Answer:
s = 'this is test'
print(len([Link]()))

19. Question: Check leap year


Answer:
y = 2024
print(y % 4 == 0 and (y % 100 != 0 or y %
400 == 0))

20. Question: Merge two dictionaries


Answer:
d1 = {'a': 1}
d2 = {'b': 2}
[Link](d2)
print(d1)
SONIYA KAUSHIK | in
21. Question: Group words by first letter
Answer:
from collections import defaultdict
words =
["apple","ant","banana","ball","cat","car"]
grouped = defaultdict(list)
for word in words:
grouped[word[0]].append(word)
print(dict(grouped))

22. Question: Find all pairs in list whose sum


equals target
Answer:
nums = [1,2,3,4,5,6,7]
target = 8

SONIYA KAUSHIK | in
pairs = [(a,b) for i,a in enumerate(nums) for
b in nums[i+1:] if a+b==target]
print(pairs)

23. Question: Convert list of tuples into


dictionary
Answer:
pairs = [("a",1),("b",2),("c",3)]
print(dict(pairs))

24. Question: Find top 3 most frequent


elements in a list
Answer:
from collections import Counter
nums = [1,2,2,3,3,3,4,4,4,4,5]
print(Counter(nums).most_common(3))

SONIYA KAUSHIK | in
25. Question: Transpose a matrix
Answer:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
transpose = [[row[i] for row in matrix] for i
in range(len(matrix[0]))]
print(transpose)

26. Question: Implement stack using Python


list
Answer:
stack = []
[Link](10)
[Link](20)
print([Link]())

27. Question: Implement queue using


[Link]

SONIYA KAUSHIK | in
Answer:
from collections import deque
queue = deque()
[Link](10)
[Link](20)
print([Link]())

28. Question: Generate random numbers


without random module
Answer:
import time
def pseudo_random(seed=1):
seed = (seed*9301+49297) % 233280
return seed/233280.0
print(pseudo_random(int([Link]())))

29. Question: Convert string to title case


SONIYA KAUSHIK | in
Answer:
text = "data science with python"
print([Link]())

30. Question: Remove punctuation from


string
Answer:
import string
text = "Hello, World! Data@Science."
clean = "".join(c for c in text if c not in
[Link])
print(clean)

31. Question: Load CSV in pandas and


display first 10 rows
Answer:
import pandas as pd

SONIYA KAUSHIK | in
df = pd.read_csv("[Link]")
print([Link](10))

32. Question: Select rows where column


value > 100
Answer:
print(df[df["Sales"] > 100])

33. Question: Drop rows with missing values


Answer:
print([Link]())

34. Question: Fill missing values with column


mean
Answer:
df["Sales"].fillna(df["Sales"].mean(),
inplace=True)

SONIYA KAUSHIK | in
35. Question: Merge two DataFrames on a
column
Answer:
df1 = [Link]({"ID":[1,2],"Name":
["A","B"]})
df2 = [Link]({"ID":[1,2],"Age":
[25,30]})
merged = [Link](df1,df2,on="ID")
print(merged)

36. Question: Group data by column and


calculate mean
Answer:
print([Link]("Category")
["Sales"].mean())

SONIYA KAUSHIK | in
37. Question: Sort DataFrame by multiple
columns
Answer:
print(df.sort_values(by=
["Category","Sales"], ascending=[True,False]))

38. Question: Apply custom function to


column
Answer:
df["Discounted"] =
df["Sales"].apply(lambda x: x*0.9)

39. Question: Find number of unique values


in a column
Answer:
print(df["CustomerID"].nunique())

SONIYA KAUSHIK | in
40. Question: Rename multiple columns in
DataFrame
Answer:
[Link](columns=
{"Sales":"Total_Sales","Date":"Order_Date"},
inplace=True)

41. Question: Create a NumPy array of zeros


Answer:
import numpy as np
arr = [Link]((3,3))
print(arr)

42. Question: Create a NumPy array from 1


to 10
Answer:
arr = [Link](1,11)
print(arr)
SONIYA KAUSHIK | in
43. Question: Reshape 1D NumPy array to 2D
Answer:
arr = [Link](1,7).reshape(2,3)
print(arr)

44. Question: Find max and min in NumPy


array
Answer:
arr = [Link]([3,7,1,9,2])
print([Link](), [Link]())

45. Question: Compute mean, median, std of


array
Answer:
arr = [Link]([1,2,3,4,5,6])
print([Link](), [Link](arr), [Link]())
SONIYA KAUSHIK | in
46. Question: Slice first 3 elements of array
Answer:
arr = [Link]([10,20,30,40,50])
print(arr[:3])

47. Question: Find index of max in NumPy


array
Answer:
arr = [Link]([4,8,2,9,6])
print([Link]())

48. Question: Create diagonal matrix in


NumPy
Answer:
arr = [Link]([1,2,3])
print(arr)
SONIYA KAUSHIK | in
49. Question: Multiply two NumPy arrays
element-wise
Answer:
a = [Link]([1,2,3])
b = [Link]([4,5,6])
print(a*b)

50. Question: Perform matrix multiplication


Answer:
a = [Link]([[1,2],[3,4]])
b = [Link]([[5,6],[7,8]])
print([Link](a,b))

51. Question: Create random NumPy array of


shape 2x3
Answer:
SONIYA KAUSHIK | in
arr = [Link](2,3)
print(arr)

52. Question: Normalize a NumPy array


Answer:
arr = [Link]([10,20,30])
norm = ([Link]())/([Link]()-[Link]())
print(norm)

53. Question: Get unique values from NumPy


array
Answer:
arr = [Link]([1,2,2,3,3,3,4])
print([Link](arr))

54. Question: Replace negative values with


zero
SONIYA KAUSHIK | in
Answer:
arr = [Link]([-2,5,-7,8])
arr[arr < 0] = 0
print(arr)

55. Question: Check for NaN in NumPy array


Answer:
arr = [Link]([1,[Link],3])
print([Link](arr))

56. Question: Convert NumPy array to


Python list
Answer:
arr = [Link]([1,2,3])
print([Link]())

SONIYA KAUSHIK | in
57. Question: Filter rows in pandas with
multiple conditions
Answer:
df = [Link]({"A":[1,2,3,4],"B":
[10,20,30,40]})
print(df[(df["A"] > 2) & (df["B"] < 40)])

58. Question: Create pivot table in pandas


Answer:
df = [Link]({"Category":
["A","A","B","B"],"Sales":[100,200,300,400]})
pivot = df.pivot_table(values="Sales",
index="Category", aggfunc="sum")
print(pivot)

59. Question: Get correlation matrix


Answer:
print([Link]())
SONIYA KAUSHIK | in
60. Question: Save DataFrame to CSV
Answer:
df.to_csv("[Link]", index=False)

61. Question: Select specific columns


Answer:
df = [Link]({"A":[1,2,3],"B":
[4,5,6],"C":[7,8,9]})
print(df[["A","C"]])

62. Question: Sort DataFrame by column


descending
Answer:
print(df.sort_values("B", ascending=False))

63. Question: Rename columns


SONIYA KAUSHIK | in
Answer:
df = [Link](columns=
{"A":"Col1","B":"Col2"})
print(df)

64. Question: Drop rows with missing values


Answer:
df = [Link]({"A":[1,None,3],"B":
[4,5,None]})
print([Link]())

65. Question: Fill missing values with mean


Answer:
df["A"].fillna(df["A"].mean(), inplace=True)
print(df)

66. Question: Convert column to datetime


SONIYA KAUSHIK | in
Answer:
df = [Link]({"Date":["2023-01-
01","2023-02-01"]})
df["Date"] = pd.to_datetime(df["Date"])
print([Link])

67. Question: Extract year and month from


datetime
Answer:
df["Year"] = df["Date"].[Link]
df["Month"] = df["Date"].[Link]
print(df)

68. Question: Remove duplicate rows


Answer:
df = [Link]({"A":[1,2,2,3],"B":
[4,5,5,6]})

SONIYA KAUSHIK | in
print(df.drop_duplicates())

69. Question: Group by column and sum


Answer:
df = [Link]({"Category":
["A","A","B"],"Sales":[100,200,300]})
print([Link]("Category")
["Sales"].sum())

70. Question: Apply custom function to


column
Answer:
df = [Link]({"A":[1,2,3]})
df["Square"] = df["A"].apply(lambda x:x**2)
print(df)

71. Question: Merge two DataFrames on key

SONIYA KAUSHIK | in
Answer:
df1 = [Link]({"ID":[1,2],"Name":
["A","B"]})
df2 = [Link]({"ID":[1,2],"Age":
[25,30]})
print([Link](df1,df2,on="ID"))

72. Question: Concatenate two DataFrames


vertically
Answer:
df1 = [Link]({"A":[1,2]})
df2 = [Link]({"A":[3,4]})
print([Link]([df1,df2]))

73. Question: Find top 2 rows by column


Answer:
df = [Link]({"A":[10,40,30,20]})

SONIYA KAUSHIK | in
print([Link](2,"A"))

74. Question: Find bottom 2 rows by column


Answer:
print([Link](2,"A"))

75. Question: Count missing values


Answer:
df = [Link]({"A":[1,None,3],"B":
[None,5,6]})
print([Link]().sum())

76. Question: Replace specific value


Answer:
df = [Link]({"A":[1,2,2,3]})
df["A"].replace(2, 99, inplace=True)
print(df)
SONIYA KAUSHIK | in
77. Question: Convert categorical to dummy
variables
Answer:
df = [Link]({"Fruit":
["Apple","Banana","Apple"]})
print(pd.get_dummies(df, columns=
["Fruit"]))

78. Question: Calculate cumulative sum


Answer:
df = [Link]({"Sales":
[100,200,300]})
df["Cumulative"] = df["Sales"].cumsum()
print(df)

79. Question: Calculate percentage of total


Answer:
SONIYA KAUSHIK | in
df["Percentage"] =
df["Sales"]/df["Sales"].sum()*100
print(df)

80. Question: Detect outliers using IQR


Answer:
Q1 = df["Sales"].quantile(0.25)
Q3 = df["Sales"].quantile(0.75)
IQR = Q3 - Q1
outliers = df[(df["Sales"] < Q1 - 1.5*IQR) |
(df["Sales"] > Q3 + 1.5*IQR)]
print(outliers)

81. Question: Standardize a numeric column


using z-score
Answer:
df["Zscore"] = (df["Sales"] -
df["Sales"].mean()) / df["Sales"].std()
SONIYA KAUSHIK | in
print(df)

82. Question: Normalize values between 0


and 1
Answer:
df["Normalized"] = (df["Sales"]-
df["Sales"].min())/(df["Sales"].max()-
df["Sales"].min())
print(df)

83. Question: Split dataset into train and test


Answer:
from sklearn.model_selection import
train_test_split
X = df[["Sales"]]
y = [0,1,0,1]
X_train,X_test,y_train,y_test =
train_test_split(X,y,test_size=0.2,random_stat
SONIYA KAUSHIK | in
e=42)
print(X_train,y_train)

84. Question: Train simple linear regression


Answer:
from sklearn.linear_model import
LinearRegression
X = [Link]([[1],[2],[3],[4]])
y = [Link]([2,4,6,8])
model = LinearRegression()
[Link](X,y)
print(model.coef_, model.intercept_)

85. Question: Make predictions


Answer:
pred = [Link]([[5]])
print(pred)
SONIYA KAUSHIK | in
86. Question: Evaluate regression using R2
score
Answer:
from [Link] import r2_score
y_true = [2,4,6,8]
y_pred = [Link](X)
print(r2_score(y_true,y_pred))

87. Question: Train logistic regression


Answer:
from sklearn.linear_model import
LogisticRegression
X = [Link]([[1],[2],[3],[4]])
y = [Link]([0,0,1,1])
clf = LogisticRegression()
[Link](X,y)
SONIYA KAUSHIK | in
print([Link]([[2.5]]))

88. Question: Create confusion matrix


Answer:
from [Link] import
confusion_matrix
y_true = [0,0,1,1]
y_pred = [0,1,1,1]
print(confusion_matrix(y_true,y_pred))

89. Question: Calculate accuracy, precision,


recall, f1-score
Answer:
from [Link] import
classification_report
print(classification_report(y_true,y_pred))

SONIYA KAUSHIK | in
90. Question: Perform k-fold cross-
validation
Answer:
from sklearn.model_selection import
cross_val_score
scores = cross_val_score(clf,X,y,cv=3)
print([Link]())

91. Question: Train decision tree classifier


Answer:
from [Link] import
DecisionTreeClassifier
clf = DecisionTreeClassifier()
[Link](X,y)
print([Link]([[2]]))

92. Question: Train random forest classifier

SONIYA KAUSHIK | in
Answer:
from [Link] import
RandomForestClassifier
clf = RandomForestClassifier()
[Link](X,y)
print([Link]([[3]]))

93. Question: Train support vector machine


classifier
Answer:
from [Link] import SVC
clf = SVC()
[Link](X,y)
print([Link]([[2.5]]))

94. Question: Scale features using


StandardScaler

SONIYA KAUSHIK | in
Answer:
from [Link] import
StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
print(X_scaled)

95. Question: Encode categorical using


LabelEncoder
Answer:
from [Link] import
LabelEncoder
fruits = ["Apple","Banana","Apple","Orange"]
encoder = LabelEncoder()
encoded = encoder.fit_transform(fruits)
print(encoded)

SONIYA KAUSHIK | in
96. Question: One-hot

encode categorical feature


Answer:
from [Link] import
OneHotEncoder
encoder = OneHotEncoder(sparse=False)
data = [Link](fruits).reshape(-1,1)
encoded = encoder.fit_transform(data)
print(encoded)

97. Question: Reduce dimensions using PCA


Answer:
from [Link] import PCA
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X_scaled)
SONIYA KAUSHIK | in
print(X_reduced)

98. Question: Save trained model with joblib


Answer:
import joblib
[Link](clf,"[Link]")

99. Question: Load trained model with joblib


Answer:
model = [Link]("[Link]")
print([Link]([[2]]))

100. Question: Create pipeline with scaler


and classifier
Answer:
from [Link] import Pipeline

SONIYA KAUSHIK | in
pipeline = Pipeline([("scaler",
StandardScaler()),("clf",
LogisticRegression())])
[Link](X,y)
print([Link]([[2.5]]))

---

SONIYA KAUSHIK | in

You might also like