wayground logo

Free Printable Worksheets

NEW

Font size

S
M
L
XL
Worksheets

DA Python 8-13 lec

Total questions: 56

Worksheet time: 28mins

Name
Class
Date
1.

How do you rotate y-axis tick labels?

plt.yticks(rotation=90)

a)

Rotates y-axis labels by 90 degrees

b)

Rotates plot

c)

Rotates x-axis

d)

Produces an error

2.

How do you change bar width in a bar plot?

df['A'].value_counts().plot.bar(width=0.3)

a)

Sets bar width to 0.3

b)

Sets spacing

c)

Changes color

d)

Produces an error

3.

How do you plot a histogram with normalized frequencies?

df['A'].plot.hist(density=True)

a)

Plots histogram normalized to form a probability density

b)

Plots raw counts

c)

Plots line plot

d)

Produces an error

4.

Which parameters control the spacing between subplots in matplotlib?

a)

wspace and hspace

b)

width_space and height_space

c)

subplot_space and grid_space

d)

padding_x and padding_y

5.

What is the default behavior for connecting points in a matplotlib line plot?

a)

Linear interpolation

b)

Cubic interpolation

c)

Step-wise connection

d)

Step-wise connection

6.

Which function is used to set the x-axis label in matplotlib?

a)

set_xlabel()

b)

set_xlim()

c)

set_xticks()

d)

set_title()

7.

Which function is used to create a legend in a plot?

a)

plt.legend()

b)

plt.show_legend()

c)

plt.add_legend()

d)

plt.legend_box()

8.

How can you customize the row and column variables in a seaborn FacetGrid?

a)

Pass them to the row and col parameters of sns.FacetGrid()

b)

Set them using grid.set_rows() and grid.set_cols()

c)

Define them in the facet_vars parameter of FacetGrid()

d)

Use the rows and columns parameters in FacetGrid()

9.

What happens to missing values in a group key during a GroupBy operation?

a)

They are excluded from the result

b)

They are replaced with zeros

c)

They are included as a separate group

d)

An error is raised

10.

When grouping by multiple keys, what is the type of the first element in the group

tuple?

a)

A tuple of key values

b)

A single key value

c)

A pandas DataFrame

d)

A list of grouped rows

11.

What does grouping by a dictionary in pandas achieve?

a)

Maps specific values to group names

b)

Creates hierarchical groups

c)

Applies multiple aggregation functions

d)

Splits groups by index levels

12.

What does the GroupBy object return when iterated over?

a)

Tuples containing the group key and group data

b)

Only the group key

c)

Only the group data

d)

Lists of grouped rows

13.

How do you apply different aggregations to different columns?

df.groupby('Category').agg({'Value':'sum','Score':'max'})

a)

Aggregates Value by sum and Score by max per group

b)

Aggregates all by sum

c)

Aggregates all by max

d)

Produces an error

14.

How do you pivot with multiple index and columns?

pd.pivot_table(df, index=['Category','SubCategory'],

columns='Region', values='Value', aggfunc='sum')

a)

Creates hierarchical index and columns, aggregating sum

b)

Creates flat index

c)

Drops Region

d)

Produces an error

15.

How do you count occurrences in crosstab?

pd.crosstab(df['Category'], df['SubCategory'])

a)

Counts frequency of each Category/SubCategory combination

b)

Sums values

c)

Computes mean

d)

Produces an error

16.

How do you count unique values per group?

df.groupby('Category')['SubCategory'].nunique()

a)

Returns number of unique SubCategory values per Category

b)

Returns total count

c)

Returns mean

d)

Produces an error

17.

Output of this code?

df.groupby('Category')['Value'].agg(['sum','count','mean'])

a)

Returns sum, count, and mean for each category

b)

Returns sum only

c)

Returns mean only

d)

Produces an error

18.

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()

a)

Sums 'Value' for each category

b)

Counts rows per category

c)

Averages 'Value' per category

d)

Produces an error

19.

How do you apply multiple aggregations and rename columns?

df.groupby('Category')['Value'].agg(Total='sum', Average='mean')

a)

Returns grouped aggregation with renamed columns

b)

Produces error in older pandas versions

c)

Aggregates sum only

d)

Aggregates mean only

20.

What will pd.to_datetime(["2018-02-29"]) return?

a)

NaT for the invalid date

b)

A ValueError due to an invalid date

c)

A datetime object representing February 28, 2018

d)

An empty DataFrame

21.

When assembling datetime objects using pd.to_datetime(df), what happens if a column

is missing (e.g., "hour")?

a)

The missing column is filled with default values (e.g., 0 for hours)

b)

An error is raised due to the missing column

c)

The operation skips rows with missing columns

d)

The DataFrame is converted without the missing field

22.

Which parameter in pd.to_datetime() allows you to set the timezone of the resulting

datetime objects?

a)

utc

b)

tz

c)

timezone

d)

localize

23.

What happens if the freq="infer" parameter fails to determine a consistent frequency?

a)

The index is created without a frequency

b)

A ValueError is raised

c)

The freq parameter defaults to daily

d)

A warning is issued

24.

Which format string correctly parses "12-11-2010 00:00"?

a)

"%d-%m-%Y %H:%M"

b)

"%Y-%m-%d %H:%M"

c)

"%d/%m/%Y %H:%M"

d)

"%m-%d-%Y %H:%M"

25.

What does the freq="M" parameter specify in pd.date_range()?

a)

Monthly frequency

b)

Minute-based frequency

c)

Monday-based weekly frequency

d)

Milliseconds frequency

26.

Which method converts a pandas period series back to timestamps?

a)

to_timestamp()

b)

to_period()

c)

to_datetime()

d)

to_dates()

27.

How do you forward-fill missing timestamps after resampling?

df.resample('H').ffill()

a)

Fills NaNs using previous available value

b)

Fills with zero

c)

Drops missing

d)

Produces error

28.

How do you compute rolling correlation between two series?

df['value'].rolling(5).corr(df['other'])

a)

Returns rolling correlation over 5-row window

b)

Returns covariance

c)

Returns sum

d)

Produces error

29.

How do you shift values using a time offset?

df['value'].shift(freq=pd.DateOffset(days=3))

a)

Shifts values 3 days along the datetime index

b)

Shifts by 3 rows

c)

Drops rows

d)

Produces error

30.

How do you create a business day date range?

pd.date_range('2020-01-01','2020-01-10', freq='B')

a)

Returns dates skipping weekends

b)

Returns all days

c)

Returns only weekends

d)

Produces error

31.

How do you shift dates with month-end offset?

df.index + pd.offsets.MonthEnd()

a)

Shifts each date to the end of month

b)

Shifts to month start

c)

Produces error

d)

Drops index

32.

How do you shift by custom business days?

df.index + pd.offsets.BDay(5)

a)

Moves index 5 business days forward

b)

Moves 5 calendar days

c)

Produces error

d)

Shifts values

33.

How do you backward-fill missing timestamps after upsampling?

df.resample('H').bfill()

a)

Fills NaNs using next valid value

b)

Fills with zero

c)

Drops rows

d)

Produces an error

34.

How do you shift values by 2 periods with shift?

df['value'].shift(2)

a)

Moves values down 2 rows

b)

Shifts index

c)

Drops rows

d)

Produces an error

35.

s = pd.Series([1,2,3], index=pd.date_range('2023-01-01',

periods=3))

s.rolling(2, min_periods=1).sum()

a)

2023-01-01 1.0 2023-01-02 3.0 2023-01-03 5.0 dtype: float64

b)

2023-

01-01 NaN 2023-01-02 3 2023-01-03 5 dtype: float64

c)

2023-01-01 1 2023-01-02 2

2023-01-03 3 dtype: int64

d)

Produces an error

36.

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()

a)

2023-01-01 1 2023-02-01 2 2023-03-01 3 Freq: MS, Name: value, dtype: int64

b)

2023-01-31 1 2023-02-28 2 2023-03-31 3 dtype: int64

c)

Produces NaNs

d)

Produces an error

37.

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()

a)

2023-01-01 10.000000 2023-01-02 16.666667 2023-01-03 26.666667 dtype: float64

b)

2023-01-01 10 2023-01-02 20 2023-01-03 30 dtype: int64

c)

2023-01-01 10

2023-01-02 15 2023-01-03 25 dtype: int64

d)

Produces an error

38.

Which of the following is a valid input for constructing a pd.DatetimeIndex?

a)

A list of ISO-8601 date strings

b)

A dictionary of date strings

c)

An integer index

d)

A set of strings

39.

How do you convert a column to datetime in pandas?

df['date'] = pd.to_datetime(df['date'])

a)

Converts the column 'date' to datetime objects

b)

Converts column to string

c)

Converts to numeric

d)

Produces an error

40.

How do you set a datetime column as index?

df.set_index('date', inplace=True)

a)

Sets 'date' column as index

b)

Drops the column

c)

Converts index to numeric

d)

Produces an error

41.

Output of this code?

df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})

df.applymap(lambda x: x**2)

a)

A B 0 1 16 1 4 25 2 9 36

b)

A B 0 1 4 1 2 5 2 3 6

c)

Produces error

42.

Output of this code?

df = pd.DataFrame({'A':[1,2,3]})

df.transform(lambda x: x*3)

a)

A 0 3 1 6 2 9

b)

A 0 1 1 2 2 3

c)

A 0 1 1 2 2 3

d)

Returns a Series

43.

What does transform return?

a)

Same shape as input DataFrame or Series

b)

Always a single value per column

c)

Always a single scalar

d)

Produces error

44.

What happens if you use map on a DataFrame?

a)

Produces an error; map works on Series

b)

Applies to all elements

c)

Applies only to first column

d)

Converts DataFrame to Series

45.

How do you convert a column to categorical?

df['col'] = df['col'].astype('category')

a)

Converts the column to categorical type

b)

Converts to string

c)

Converts to numeric

d)

Produces an error

46.

What is z-score?

a)

Number of standard deviations a value is from the mean

b)

Difference between median and mean

c)

Ratio of max to min

d)

Range of data

47.

Output of this code?

from scipy.stats import zscore

import pandas as pd

s = pd.Series([1,2,3,4,5])

zscore(s)

a)

array([-1.41421356, -0.70710678, 0., 0.70710678, 1.41421356])

b)

array([1,2,3,4,5])

c)

array([0,0,0,0,0])

d)

Produces error

48.

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)

A B A 1.0 -1.0 B -1.0 1.0

b)

A B A 1.0 1.0 B 1.0 1.0

c)

Produces error

d)

A B A 0.5 -0.5 B -0.5 0.5

49.

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)

a)

4 0.4 3 0.3 2 0.2 1 0.1 dtype: float64

b)

4 4 3 3 2 2 1 1 dtype: int64

c)

Produces error

d)

1 0.1 2 0.2 3 0.3 4 0.4

50.

Output of this code?

s = pd.Series([1,2,3,4,5])

np.cumsum((s - s.mean())**2)

a)

Series of cumulative squared deviations

b)

Series of cumulative sums

c)

Series of cumulative means

d)

Produces error

51.

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()

a)

Standardized ranks of each column

b)

Z-scores of original values

c)

Normalized values between 0 and 1

d)

Produces error

52.

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()

a)

cat A 2.0 B 3.0 C 5.0 Name: val, dtype: float64

b)

cat A 2.0 B 2.0 C 5.0 Name: val, dtype: float64

c)

Produces error

d)

Returns DataFrame instead of Series

53.

What does this code compute?

df['val'].rolling(2, min_periods=1).apply(lambda x: np.prod(x))

<variantright> What does this code compute?

df['val'].rolling(2, min_periods=1).apply(lambda x: np.prod(x))

a)

Rolling product of values over a 2-row window, computing even if only 1 value is

present

b)

Rolling sum over 2 rows

c)

Cumulative product

d)

Produces error

54.

What is the output?

df['cat'] = df['cat'].astype('category')

df['cat'].cat.codes

a)

0 0 1 1 2 0 3 1 4 2 dtype: int8

b)

Produces error

c)

Returns

original values

d)

Returns strings of categories

55.

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()

a)

date

2023-01-01 3.0

2023-01-03 3.0

2023-01-05 5.0

Freq: 2D, Name: val, dtype: float64

b)

Produces error

c)

Returns cumulative sum instead

d)

Returns original daily values

56.

Output of this code?

df['val_z'] = (df['val'] - df['val'].mean()) / df['val'].std()

df.groupby('cat')['val_z'].mean()

a)

cat A 0.0 B 0.0 C 0.0 Name: val_z, dtype: float64

b)

Produces error

c)

Returns original val

d)

Non-zero values