WorksheetsDA Python 1-7 lec
Total questions: 51
Worksheet time: 26mins
What is the output of the following code?
t = (1, 2, 3) + (4, 5)
print(t)
(1, 2, 3, 4, 5)
(5, 4, 3, 2, 1)
[1, 2, 3, 4, 5]
(1, 2, 3), (4, 5)
What method is used to remove a specific value from a list?
remove()
pop()
delete()
del
The ______ function returns a new sorted list from any sequence.
sorted
sort
remove
del
The update method is used to merge one dictionary into another.
True
False
Which method is used to check if a dictionary contains a specific key?
in
contains()
has_key()
key_check()
The pandas library provides high-level data structures for working with structured and tabular data.
True
False
Which of the following is a mutable object in Python?
List
None
String
Tuple
What will be the output of this code? x = 10; y = 3; print(x // y)
3.33
3
3.0
4
Output of this code:
nums = [1,2,3]
print(sum(nums))
Error
6
5
3
What does the following code print?
a = [1,2,3]
print(a[::-1])
[3,2,1]
[1,2,3]
[1,3,2]
Error
Output of this code:
d = {"a":1, "b":2}
print(d.get("c", 0))
0
None
Error
2
What does the following code return?
lst = [1,2,3,4]
print(lst.index(3))
2
3
1
Error
The with statement is used to handle ______ safely and ensure they are closed properly.
files
tuples
close
ensure
Which of the following is not a valid input for creating a DataFrame?
A single integer
A dictionary of lists
A NumPy array
A list of dictionaries
What is the output of the following code?
import numpy as np
a = np.array([1, 2, 3])
print(a[1])
2
1
3
Error
What does this code print?
import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a.shape)
(2, 2)
(2,)
(4,)
Error
Output of the following code?
import numpy as np
a = np.array([1,2,3])
print(a.dtype)
int64
float64
object
error
What is the result?
import numpy as np
a = np.zeros((2,3))
[[0. 0. 0.]
[0. 0. 0.]]
[0. 0. 0.]
[[0. 0.]
[0. 0. ]
[0. 0.]]
Error
Output of this code?
import numpy as np
a = np.array([1,2,3,4])
print(np.where(a>2))
(array([2,3]),)
(array([0,1]),)
[3 4]
Error
What does this print?
import numpy as np
a = np.array([1,2,3,4])
print(np.unique([1,2,2,3,3,4]))
[1 2 3 4]
[1 2 2 3 3 4]
[2 3 4]
Error
What is a key difference between a pandas `Series` and a `DataFrame`?
A `Series` is one-dimensional, while a `DataFrame` is two-dimensional.
A `Series` can contain multiple data types, while a `DataFrame` cannot.
A `DataFrame` does not have indexes, while a `Series` always does.
Both `Series` and `DataFrame` are always empty by default.
Which method allows you to select data from a DataFrame by row and column labels?
`loc`
`iloc`
`index`
`slice`
What will the following code output?
import pandas as pd
data = {"A": [1, 2], "B": [3, 4]}
df = pd.DataFrame(data)
print(df.iloc[1])
A 2, B 4
A 1, B 3
[1, 3]
Error: No row with index 1
What will the following code output?
import pandas as pd
s = pd.Series([1, 2, 3], index=["a", "b", "c"])
print(s["b"])
2
1
"b"
Error: Invalid index access
What does this code return?
import pandas as pd
df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]})
print(df[df['A']>1])
A B
1 2 5
2 3 6
A B
0 1 4
[2, 3]
Error
Output of this code?
import pandas as pd
df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]})
print(df.iloc[1,1])
5
2
4
Error
What does the following code produce?
import pandas as pd
df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]})
print(df.loc[0,'B'])
4
1
0
Error
Which library is typically used to read and parse Excel files in pandas?
openpyxl
pickle
lxml
lxml
Which pandas method writes a DataFrame to pickle format?
to_pickle()
write_pickle()
write_pickle()
pickle_dump()
What will the following code do?
import pandas as pd
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
print(df.head())
Prints the first 5 rows of the Excel sheet
Reads only the first row
Writes CSV without header
How do you remove rows with all NaN values?
df.dropna(how='all', inplace=True)
Drops rows where all values are NaN
Drops any row with NaN
Drops column with NaN
Fills NaN
How can you strip special characters from a string column?
df['col'] = df['col'].str.replace('[^a-zA-Z0-9]', ' ', regex=True)
Removes all non-alphanumeric characters
Converts to lowercase
Converts to uppercase
Replaces spaces with underscores
Output of this code?
import pandas as pd
df = pd.DataFrame({'A':[1,2,3,4,5]})
Q1 = df['A'].quantile(0.25)
Q3 = df['A'].quantile(0.75)
IQR = Q3 - Q1
df_filtered = df[(df['A'] >= Q1 - 1.5*IQR) & (df['A'] <= Q3 +
1.5*IQR)]
print(df_filtered)
Filters out outliers based on IQR
Keeps only outliers
Drops all rows
Error
How do you replace all infinite values with NaN?
import numpy as np
df.replace([np.inf, -np.inf], np.nan, inplace=True)
Replaces +inf/-inf with NaN
Drops infinite values
Converts to zero
Raises error
Converts numbers like '1,000' to 1000
Treats ',' as delimiter
Reads all values as strings
Error
Ignores blank lines in the CSV
Reads blank lines as NaN
Error
Deletes CSV
Prevents dtype guessing and ensures proper memory usage
Reads CSV in chunks
Converts everything to string
Error
What does this code do?
import pandas as pd
df = pd.read_sql('SELECT * FROM table1', conn, index_col='ID')
Reads SQL table and sets 'ID' as index
Writes SQL table
Converts SQL table to CSV
Creates a new SQL table
What does this code do?
import pandas as pd
df = pd.read_csv('data.csv', header=span>None)
print(df.head())
Reads only the first row
Writes CSV without header
Reads CSV without using the first row as header
Reads CSV using the first row as header
What does this code do?
df['col'] = df['col'].str.lower()
Converts all strings in the column to lowercase
Converts to uppercase
Strips spaces
Deletes column
How can you remove columns with more than 50% missing values?
df.dropna(thresh=len(df)*0.5, axis=1, inplace=True)
Drops columns with more than 50% NaN
Drops rows with >50% NaN
Replaces NaN with 0
Keeps only rows with >50% non-NaN
What does this code produce?
import pandas as pd
df1 = pd.DataFrame({'key':[1,2,3],'A':[10,20,30]})
df2 = pd.DataFrame({'key':[3,4,5],'B':[300,400,500]})
pd.concat([df1, df2], axis=0, ignore_index=True)
Stacks df1 and df2 vertically and resets the index
Stacks horizontally
Performs a merge
Produces an error
What is the result of this code?
import pandas as pd
df = pd.DataFrame({'X':[1,2],'Y':[3,4]})
pd.melt(df, id_vars=['X'])
Keeps 'X' fixed and unpivots 'Y' into long format
Keeps 'Y' fixed and unpivots 'X'
Drops column 'Y'
Produces an error
What does this code do?
import pandas as pd
df1 = pd.DataFrame({'key':[1,2,3],'A':[10,20,30]})
df2 = pd.DataFrame({'key':[2,3,4],'B':[200,300,400]})
pd.merge(df1, df2, how='outer', on='key')
Outer join: keeps all keys from both DataFrames, fills missing with NaN
Left join
Inner join
Right join
Output of this code?
import pandas as pd
df = pd.DataFrame({'id':[1,1,2,2],'variable':['X','Y','X','Y'],'value':[ 10,20,30,40]}
df.pivot(index='id', columns='variable', values='value')
Produces an error
Drops column 'value'
Reshapes from wide to long
Reshapes from long to wide format with 'id' as index
What is the difference between merge and concat?
merge joins based on columns or keys, concat stacks DataFrames along axis
merge concatenates, concat joins
Both do the same thing
merge deletes duplicates, concat does not
How can you reorder levels in a MultiIndex?
df.reorder_levels([1,0])
Switches the positions of the levels
Sorts the index
Drops a level
Creates a new column
What is the key difference between reorder_levels() and swaplevel() in hierarchical
indexing?
reorder_levels() allows arbitrary reordering of index levels, while swaplevel() only swaps
two levels
swaplevel() can reorder multiple levels, while reorder_levels() swaps levels
eorder_levels() can be used on non-hierarchical indexes, while swaplevel() cannot
swaplevel() requires specifying all levels, while reorder_levels() defaults to the first two
In a merge() operation, what does the how='outer' parameter do?
Performs a union of the keys from both DataFrames, including all rows from both
Includes only rows with keys present in both DataFrames
Includes rows from the left DataFrame only
Includes rows from the right DataFrame only
Output of this code?
import pandas as pd
arrays = [['A','A','B','B'], [1,2,1,2]]
index = pd.MultiIndex.from_arrays(arrays, names=('letter','num'))
df = pd.DataFrame({'val':[10,20,30,40]}, index=index)
df.loc['A']
Selects all rows where first level of MultiIndex is 'A'
Selects rows where second level is 'A'
Returns columns named 'A'
Produces an error
Output of this code?
import pandas as pd
df = pd.DataFrame({'id':[1,1,2,2],'variable':['X','Y','X','Y'],'value':[ 10,20,30,40]})
df.pivot(index='id', columns='variable', values='value')
Reshapes from long to wide format with 'id' as index
Reshapes from wide to long
Drops column 'value'
Produces an error
