NEW
Font size
WorksheetsDA Python 8-13 lec
Total questions: 56
Worksheet time: 28mins
How do you rotate y-axis tick labels?
plt.yticks(rotation=90)
Rotates y-axis labels by 90 degrees
Rotates plot
Rotates x-axis
Produces an error
How do you change bar width in a bar plot?
df['A'].value_counts().plot.bar(width=0.3)
Sets bar width to 0.3
Sets spacing
Changes color
Produces an error
How do you plot a histogram with normalized frequencies?
df['A'].plot.hist(density=True)
Plots histogram normalized to form a probability density
Plots raw counts
Plots line plot
Produces an error
Which parameters control the spacing between subplots in matplotlib?
wspace and hspace
width_space and height_space
subplot_space and grid_space
padding_x and padding_y
What is the default behavior for connecting points in a matplotlib line plot?
Linear interpolation
Cubic interpolation
Step-wise connection
Step-wise 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?
How can you customize the row and column variables in a seaborn FacetGrid?
Pass them to the row and col parameters of sns.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()
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 count occurrences in crosstab?
pd.crosstab(df['Category'], df['SubCategory'])
Counts frequency of each Category/SubCategory combination
Sums values
Computes mean
Produces an error
How do you count unique values per group?
df.groupby('Category')['SubCategory'].nunique()
Returns number of unique SubCategory values per Category
Returns total count
Returns mean
Produces an error
Output of this code?
df.groupby('Category')['Value'].agg(['sum','count','mean'])
Returns sum, count, and mean for each category
Returns sum only
Returns mean only
Produces an error
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()
Sums 'Value' for each category
Counts rows per category
Averages 'Value' per category
Produces an error
How do you apply multiple aggregations and rename columns?
df.groupby('Category')['Value'].agg(Total='sum', Average='mean')
Returns grouped aggregation with renamed columns
Produces error in older pandas versions
Aggregates sum only
Aggregates mean only
What will pd.to_datetime(["2018-02-29"]) return?
NaT for the invalid date
A ValueError due to an invalid date
A datetime object representing February 28, 2018
An empty DataFrame
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?
The index is created without a frequency
A ValueError is raised
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 rolling correlation over 5-row window
Returns covariance
Returns sum
Produces error
How do you shift values using a time offset?
df['value'].shift(freq=pd.DateOffset(days=3))
Shifts values 3 days along the datetime index
Shifts by 3 rows
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 dates skipping weekends
Returns all days
Returns only weekends
Produces error
How do you shift dates with month-end offset?
df.index + pd.offsets.MonthEnd()
Shifts each date to the end of month
Shifts to month start
Produces error
Drops index
How do you shift by custom business days?
df.index + pd.offsets.BDay(5)
Moves index 5 business days forward
Moves 5 calendar days
Produces error
Shifts values
How do you backward-fill missing timestamps after upsampling?
df.resample('H').bfill()
Fills NaNs using next valid value
Fills with zero
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
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','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 the column 'date' to datetime objects
Converts column to string
Converts to numeric
Produces an error
How do you set a datetime column as index?
df.set_index('date', inplace=True)
Sets 'date' column as index
Drops the column
Converts index to numeric
Produces an error
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 1 2 2 3
A 0 1 1 2 2 3
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
cat A 2.0 B 2.0 C 5.0 Name: val, dtype: float64
Produces error
Returns DataFrame instead of Series
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
