WorksheetsPython
Total questions: 108
Worksheet time: 54mins
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
arrange
order
sorter
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?
String
Tuple
List
None
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))
6
5
3
Error
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
loops
variables
exceptions
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])
1
2
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)
float64
int64
object
Error
What is the result? import numpy as np a = np.zeros((2,3))
0 0 0
0 0 0
0 0 0
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?
```python
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: Invalid index access
What will the following code output?
```python
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
What does this code return?
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
json
Which pandas method writes a DataFrame to pickle format?
to_pickle()
write_pickle()
to_binary()
pickle_dump()
What will the following code do? import pandas as pd df = pd.read_excel('data.xlsx', sheet_name='Sheet1') print(df.head())
It will read the 'Sheet1' sheet from 'data.xlsx' into a DataFrame and print the first five rows.
It will print the entire contents of 'data.xlsx'.
It will create a new Excel file named 'data.xlsx'.
It will print the last five rows of 'Sheet1' from 'data.xlsx'.
What does this code output? import pandas as pd df = pd.read_csv('data.csv', thousands=',')
Converts numbers like '1,000' to 1000
Treats ',' as delimiter
Reads all values as strings
Error
Output of this code? import pandas as pd df = pd.read_csv('data.csv', skip_blank_lines=True)
Ignores blank lines in the CSV
Reads blank lines as NaN
Error
Deletes CSV
What is the output of this code? import pandas as pd df = pd.read_csv('data.csv', low_memory=False)
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=None)
print(df.head())
Reads CSV without using the first row as header
Reads CSV using the first row as header
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
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?
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')
Left join
Inner join
Right join
Outer 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')
Reshapes from wide to long
Reshapes from long to wide format with 'id' as index
Drops column 'value'
Produces an error
What type of join is described?
keeps all rows from df1, adds matching rows from df2
Inner join
Right join
Outer join
Left join
What is the difference between merge and concat?
merge concatenates, concat joins
Both do the same thing
merge deletes duplicates, concat does not
merge joins based on columns or keys, concat stacks DataFrames along axis
How can you reorder levels in a MultiIndex? df.reorder_levels([1,0])
Sorts the index
Switches the positions of the levels
Drops a level
Creates a new column
Что является ключевым отличием между reorder_levels() и swaplevel() в иерархической индексации?
swaplevel() может переупорядочить несколько уровней, в то время как reorder_levels() меняет местами уровни
reorder_levels() может использоваться на неиерархических индексах, в то время как swaplevel() не может
reorder_levels() позволяет произвольное переупорядочение уровней индекса, в то время как swaplevel() только меняет местами два уровня
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
How do you rotate y-axis tick labels?
Rotates y-axis labels by 90 degrees
Rotates x-axis
Rotates plot
Produces an error
How do you change bar width in a bar plot?
df['A'].value_counts().plot.bar(width=0.3)
Sets spacing
Changes color
Produces an error
Sets bar width to 0.3
How do you plot a histogram with normalized frequencies?
df['A'].plot.hist(density=True)
Plots raw counts
Plots histogram normalized to form a probability density
Plots line plot
Produces an error
Which parameters control the spacing between subplots in matplotlib?
width_space and height_space
subplot_space and grid_space
padding_x and padding_y
wspace and hspace
What is the default behavior for connecting points in a matplotlib line plot?
Linear interpolation
Cubic interpolation
Step-wise connection
No connection
Which function is used to set the x-axis label in matplotlib?
set_xlabel()
set_xlim()
set_xticks()
set_title()
Which function is used to create a legend in a plot?
plt.legend()
plt.show_legend()
plt.add_legend()
plt.legend_box()
How can you customize the row and column variables in a seaborn FacetGrid?
Set them using grid.set_rows() and grid.set_cols()
Define them in the facet_vars parameter of FacetGrid()
Use the rows and columns parameters in FacetGrid()
Pass them to the row and col parameters of sns.FacetGrid()
What happens to missing values in a group key during a GroupBy operation?
They are excluded from the result
They are replaced with zeros
They are included as a separate group
An error is raised
When grouping by multiple keys, what is the type of the first element in the group tuple?
A tuple of key values
A single key value
A pandas DataFrame
A list of grouped rows
What does grouping by a dictionary in pandas achieve?
Maps specific values to group names
Creates hierarchical groups
Applies multiple aggregation functions
Splits groups by index levels
What does the GroupBy object return when iterated over?
Tuples containing the group key and group data
Only the group key
Only the group data
Lists of grouped rows
How do you apply different aggregations to different columns?
df.groupby('Category').agg({'Value':'sum','Score':'max'})
Aggregates Value by sum and Score by max per group
Aggregates all by sum
Aggregates all by max
Produces an error
How do you pivot with multiple index and columns?
pd.pivot_table(df, index=['Category','SubCategory'], columns='Region', values='Value', aggfunc='sum')
Creates hierarchical index and columns, aggregating sum
Creates flat index
Drops Region
Produces an error
How do you pivot with multiple index and columns?
pd.pivot_table(df, index=['Category','SubCategory'], columns='Region', values='Value', aggfunc='sum')
Counts frequency of each Category/SubCategory combination
Sums values
Computes mean
Produces an error
Output of this code?
df.groupby('Category')['Value'].agg(['sum','count','mean'])
Returns sum only
Returns mean only
Produces an error
Returns sum, count, and mean for each category
What does this code produce? import pandas as pd df = pd.DataFrame({'Category':['A','B','A','B'],'Value':[10,20,30,40]}) df.groupby('Category').sum()
Counts rows per category
Averages 'Value' per category
Produces an error
Sums 'Value' for each category
How do you apply multiple aggregations and rename columns?
df.groupby('Category')['Value'].agg(Total='sum', Average='mean')
Produces error in older pandas versions
Aggregates sum only
Aggregates mean only
Returns grouped aggregation with renamed columns
What will pd.to_datetime(["2018-02-29"]) return?
NaT for the invalid date
A datetime object representing February 28, 2018
An empty DataFrame
A ValueError due to an invalid date
When assembling datetime objects using pd.to_datetime(df), what happens if a column is missing (e.g., "hour")?
The missing column is filled with default values (e.g., 0 for hours)
An error is raised due to the missing column
The operation skips rows with missing columns
The DataFrame is converted without the missing field
Which parameter in pd.to_datetime() allows you to set the timezone of the resulting datetime objects?
utc
tz
timezone
localize
What happens if the freq="infer" parameter fails to determine a consistent frequency?
A ValueError is raised
The index is created without a frequency
The freq parameter defaults to daily
A warning is issued
Which format string correctly parses "12-11-2010 00:00"?
"%d-%m-%Y %H:%M"
"%Y-%m-%d %H:%M"
"%d/%m/%Y %H:%M"
"%m-%d-%Y %H:%M"
What does the freq="M" parameter specify in pd.date_range()?
Monthly frequency
Minute-based frequency
Monday-based weekly frequency
Milliseconds frequency
Which method converts a pandas period series back to timestamps?
to_timestamp()
to_period()
to_datetime()
to_dates()
How do you forward-fill missing timestamps after resampling?
df.resample('H').ffill()
Fills NaNs using previous available value
Fills with zero
Drops missing
Produces error
How do you compute rolling correlation between two series?
df['value'].rolling(5).corr(df['other'])
Returns covariance
Returns sum
Returns rolling correlation over 5-row window
Produces error
How do you shift values using a time offset?
df['value'].shift(freq=pd.DateOffset(days=3))
Shifts by 3 rows
Shifts values 3 days along the datetime index
Drops rows
Produces error
How do you create a business day date range?
pd.date_range('2020-01-01','2020-01-10', freq='B')
Returns all days
Returns dates skipping weekends
Returns only weekends
Produces error
How do you shift dates with month-end offset?
df.index + pd.offsets.MonthEnd()
Shifts to month start
Shifts each date to the end of month
Produces error
Drops index
How do you shift by custom business days?
df.index + pd.offsets.BDay(5)
Moves 5 calendar days
Moves index 5 business days forward
Produces error
Shifts values
How do you backward-fill missing timestamps after upsampling?
df.resample('H').bfill()
Fills with zero
Fills NaNs using next valid value
Drops rows
Produces an error
How do you shift values by 2 periods with shift?
df['value'].shift(2)
Moves values down 2 rows
Shifts index
Drops rows
Produces an error
What will be the output? s = pd.Series([1,2,3], index=pd.date_range('2023-01-01', periods=3)) s.rolling(2, min_periods=1).sum()
2023-01-01 1.0 2023-01-02 3.0 2023-01-03 5.0 dtype: float64
2023-01-01 NaN 2023-01-02 3 2023-01-03 5 dtype: float64
2023-01-01 1 2023-01-02 2 2023-01-03 3 dtype: int64
Produces an error
What will be the output? df = pd.DataFrame({'value':[1,2,3]}, index=pd.period_range('2023-01-01','2023-03', freq='M')) df.index.to_timestamp()
2023-01-01 1 2023-02-01 2 2023-03-01 3 Freq: MS, Name: value, dtype: int64
2023-01-31 1 2023-02-28 2 2023-03-31 3 dtype: int64
Produces NaNs
Produces an error
What will be the output? s = pd.Series([10,20,30], index=pd.date_range('2023-01-01', periods=3)) s.ewm(span=2).mean()
2023-01-01 10.000000 2023-01-02 16.666667 2023-01-03 26.666667 dtype: float64
2023-01-01 10 2023-01-02 20 2023-01-03 30 dtype: int64
2023-01-01 10 2023-01-02 15 2023-01-03 25 dtype: int64
Produces an error
Which of the following is a valid input for constructing a pd.DatetimeIndex?
A list of ISO-8601 date strings
A dictionary of date strings
An integer index
A set of strings
How do you convert a column to datetime in pandas?
df['date'] = pd.to_datetime(df['date'])
Converts column to string
Converts to numeric
Produces an error
Converts the column 'date' to datetime objects
How do you set a datetime column as index?
df.set_index('date', inplace=True)
Drops the column
Converts index to numeric
Produces an error
Sets 'date' column as index
Output of this code?
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df.applymap(lambda x: x**2)
A B 0 1 16 1 4 25 2 9 36
A B 0 1 4 1 2 5 2 3 6
Produces error
Output of this code?
df = pd.DataFrame({'A':[1,2,3]})
df.transform(lambda x: x*3)
A 0 3 1 6 2 9
A 0 1 2 2 3
Produces error
Returns a Series
What does transform return?
Same shape as input DataFrame or Series
Always a single value per column
Always a single scalar
Produces error
What happens if you use map on a DataFrame?
Produces an error; map works on Series
Applies to all elements
Applies only to first column
Converts DataFrame to Series
How do you convert a column to categorical?
df['col'] = df['col'].astype('category')
Converts the column to categorical type
Converts to string
Converts to numeric
Produces an error
What is z-score?
Number of standard deviations a value is from the mean
Difference between median and mean
Ratio of max to min
Range of data
Output of this code?
from scipy.stats import zscore
import pandas as pd
s = pd.Series([1,2,3,4,5])
zscore(s)
array([-1.41421356, -0.70710678, 0., 0.70710678, 1.41421356])
array([1,2,3,4,5])
array([0,0,0,0,0])
Produces error
What will be the output of this code?
import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[1,2,3,4,5], 'B':[5,4,3,2,1]})
df.corr(method='kendall')
A B A 1.0 -1.0 B -1.0 1.0
A B A 1.0 1.0 B 1.0 1.0
Produces error
A B A 0.5 -0.5 B -0.5 0.5
What will be the output of this code?
s = pd.Series([1,2,2,3,3,3,4,4,4,4])
s.value_counts(normalize=True)
4 0.4 3 0.3 2 0.2 1 0.1 dtype: float64
4 4 3 3 2 2 1 1 dtype: int64
Produces error
1 0.1 2 0.2 3 0.3 4 0.4
Output of this code?
s = pd.Series([1,2,3,4,5])
np.cumsum((s - s.mean())**2)
Series of cumulative squared deviations
Series of cumulative sums
Series of cumulative means
Produces error
What does this code compute?
df = pd.DataFrame({'X':[1,2,3,4,5], 'Y':[5,4,3,2,1]})
(df.rank() - df.mean())/df.std()
Standardized ranks of each column
Z-scores of original values
Normalized values between 0 and 1
Produces error
What will be the output of this code?
import pandas as pd
import numpy as np
df = pd.DataFrame({
'date': pd.date_range('2023-01-01', periods=5),
'val': [1, np.nan, 3, np.nan, 5],
'cat': ['A','B','A','B','C']
})
df['val'] = df['val'].interpolate(method='linear')
df.groupby('cat')['val'].mean()
cat A 2.0 B 3.0 C 5.0 Name: val, dtype: float64
Produces error
Returns DataFrame instead of Series
What does this code compute?
df['val'].rolling(2, min_periods=1).apply(lambda x: np.prod(x))
Rolling product of values over a 2-row window, computing even if only 1 value is present
Rolling sum over 2 rows
Cumulative product
Produces error
0 0 1 1 2 0 3 1 4 2 dtype: int8
Produces error
Returns original values
Returns strings of categories
What is the result of this multi-step operation?
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
df.resample('2D')['val'].sum()
date
2023-01-01 3.0
2023-01-03 3.0
2023-01-05 5.0
Freq: 2D, Name: val, dtype: float64
Produces error
Returns cumulative sum instead
Returns original daily values
Output of this code?
df['val_z'] = (df['val'] - df['val'].mean()) / df['val'].std()
df.groupby('cat')['val_z'].mean()
cat A 0.0 B 0.0 C 0.0 Name: val_z, dtype: float64
Produces error
Returns original val
Non-zero values
