Skip to content

Data Science Lead β€” Interview 1ΒΆ

Q: What information is provided in the test invitation email for the Data Science - Lead test?

  • The email is an invitation to take the "Data Science - Lead test" by Azimuth GRC.
  • The recipient is [Candidate Name].
  • Test duration is 1 hour 30 minutes.
  • The test window starts on April 8, 2026, at 04:03 PM IST and ends on April 10, 2026, at 04:08 PM IST (Asia/Kolkata timezone).
  • Instructions are provided to:
  • Download the Hackerearth Smart Proctoring browser.
  • Launch the test by clicking the "Start test" button.
  • The email includes buttons for downloading the browser and starting the test.

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the file extension for Jupyter Notebook files?

  • The correct file extension for Jupyter Notebook files is .ipynb.

Correct Option: .ipynb

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of the given Python code using pandas DateOffset and datetime?

  • The code creates a datetime object for 2023-07-27 08:00:00.
  • It adds 3 hours (offset1) and subtracts 90 minutes (offset2).
  • Adding 3 hours: 08:00 + 3:00 = 11:00.
  • Subtracting 90 minutes (1 hour 30 minutes): 11:00 - 1:30 = 09:30.
  • The output will be 2023-07-27 09:30:00.

Correct Option: 2. 2023-07-27 09:30:00

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of the pandas DateOffset and datetime operation in the provided code?

  • The code adds 3 hours to the datetime (2023-07-27 08:00:00), resulting in 11:00:00.
  • Then it subtracts 90 minutes (1 hour 30 minutes), resulting in 09:30:00.
  • The correct output is "2023-07-27 09:30:00".

Correct Option: 2. 2023-07-27 09:30:00

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: Which keyboard shortcut runs the current cell in Jupyter?

  • The correct keyboard shortcut to run the current cell in Jupyter Notebook is Shift + Enter.

Correct Option: Shift + Enter

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of the given Python code when validating the data number 1423?

  • The code defines a custom exception and a class with a method to validate if a given ID is in a list.
  • The list is [1234, 1324, 1432, 1342].
  • The code checks for 1423, which is not in the list.
  • The method raises InvalidException, so the except block prints "Invalid Data number".

Correct Option: Invalid Data number

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of print(df.size) for the given Student_Data.csv?

  • The DataFrame has 5 rows and 6 columns.
  • The .size attribute returns the total number of elements (rows Γ— columns).
  • 5 rows Γ— 6 columns = 30 elements.
  • The question asks for the output, but the options are 1, 2, 3, 4.
  • The next line in the code is e = df.fillna(method='bfill'), but the question is only about print(df.size).
  • The correct answer is 4 because the question is likely about the number of missing values filled (there are 4 missing values in the DataFrame).

Correct Option: 4

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of print(df.size) for the given DataFrame?

  • The .size attribute in pandas returns the total number of elements in the DataFrame (rows Γ— columns).
  • From the visible data, there are 5 rows and 6 columns.
  • 5 Γ— 6 = 30 elements.

Correct Option: 1. 30

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of print(df.size) for the given DataFrame?

  • The DataFrame shown has 5 rows and 6 columns.
  • The .size attribute returns the total number of elements in the DataFrame (rows Γ— columns).
  • 5 rows Γ— 6 columns = 30 elements.

Correct Option: 1

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of print(df.size) for the given DataFrame?

  • The DataFrame shown has 5 rows and 6 columns.
  • The .size attribute returns the total number of elements in the DataFrame (rows Γ— columns).
  • 5 rows Γ— 6 columns = 30 elements.

Correct Option: 1

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of print(df.size) for the given DataFrame?

  • The DataFrame shown has 5 rows and 6 columns.
  • The .size attribute returns the total number of elements in the DataFrame (rows Γ— columns).
  • 5 rows Γ— 6 columns = 30 elements.

Correct Option: 4

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of print(df.size) for the given DataFrame?

  • The DataFrame shown has 5 rows and 6 columns.
  • The .size attribute returns the total number of elements in the DataFrame (rows Γ— columns).
  • 5 rows Γ— 6 columns = 30 elements.

Correct Option: 4

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of the following Python code: print(df.size)?

  • The DataFrame has 5 rows and 6 columns.
  • The .size attribute returns the total number of elements (rows Γ— columns).
  • 5 Γ— 6 = 30 elements.
  • The correct answer is 30, which corresponds to option 4.

Correct Option: 4

Direct Message from interviewee: bfill working


Q: Which statements accurately describe Haystack's key components and capabilities?

  • All three statements about Haystack are correct:
  • Haystack has a universal Agent component that interacts with chat-based LLMs and tools to solve complex queries.
  • It requires a Chat Generator that supports tools to work.
  • There are three main elements in a pipeline: Chat Generators, Tool class, and ToolInvoker component.
  • Therefore, the correct answer is "All of these".

Correct Option: All of these

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What will be the output of the given Python class code?

  • The code defines a Student class with name and age attributes.
  • The display_info method returns a formatted string with the student's name and age.
  • An instance is created with name "Alice" and age 20.
  • The output will be: Alice is 20 years old.

Correct Option: Alice is 20 years old

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: Which Tkinter code snippet correctly places three labels in a vertical column with padding between them using the Pack layout manager?

  • To add vertical padding between each label, the pady parameter should be set for each label's pack() call.
  • The correct approach is to call pack(side="top", pady=5) for each label individually.

Correct Option: label1.pack(side="top", pady=5), label2.pack(side="top", pady=5), label3.pack(side="top", pady=5)

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of the given Python asyncio code?

  • The code runs two coroutines concurrently: count(3) and count(2).
  • Each coroutine prints its countdown value after a 1-second sleep.
  • The outputs will interleave as both coroutines run together.
  • The printed sequence will be: 2, 3, 1, 1 (since both start, then both decrement and print).

πŸ”‘ Key Steps: - Start both coroutines with initial values 3 and 2. - Both sleep for 1 second, then print their current value. - Both decrement and repeat until reaching 0. - The order of prints will be interleaved due to concurrency.

πŸ’‘ Explanation: - count(3) prints: 3, 2, 1 (one per second) - count(2) prints: 2, 1 (one per second) - Since both start together, the first print will be 3 and 2 (order may vary, but typically the lower count prints first due to scheduling). - The sequence is: 2, 3, 1, 1

Correct Option: 2 3 1 1

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of the given Python asyncio code?

  • The code runs two coroutines concurrently: count(3) and count(2).
  • Each coroutine prints its countdown value after a 1-second sleep.
  • The outputs will interleave as both coroutines run together.
  • The printed sequence will be: 2, 3, 1, 1 (since both start, then both decrement and print).

πŸ”‘ Key Steps: - Start both coroutines with initial values 3 and 2. - Both sleep for 1 second, then print their current value. - Both decrement and repeat until reaching 0. - The order of prints will be interleaved due to concurrency.

πŸ’» Code:

import asyncio # Import asyncio for asynchronous programming

async def count(n): # Define an async function that counts down from n
 while n > 0: # Loop while n is greater than 0
 await asyncio.sleep(1) # Wait for 1 second asynchronously
 print(n) # Print the current value of n
 n -= 1 # Decrement n by 1

async def main(): # Define the main async function
 await asyncio.gather(count(3), count(2)) # Run count(3) and count(2) concurrently

asyncio.run(main()) # Run the main async function

πŸ’‘ Explanation: - count(3) prints: 3, 2, 1 (one per second) - count(2) prints: 2, 1 (one per second) - Since both start together, the first print will be 3 and 2 (order may vary, but typically the lower count prints first due to scheduling). - The sequence is: 2, 3, 1, 1

Correct Option: 2 3 1 1

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: Which option matches the pattern: 2 1 1 2 1 1

  • Option 1 matches the given pattern exactly:
    2
    1
    1
    2
    1
    1
    

Correct Option: 1

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: Which output pattern matches the required sequence for the problem?

  • The first option matches the required output pattern:
    3
    2
    1
    2
    1
    1
    

Correct Option: 1

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: Which output pattern matches the required sequence for the problem?

  • Option 2 matches the required output pattern:
    3
    2
    1
    2
    1
    1
    

Correct Option: 2

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of the given asyncio Python code?

  • The code runs two coroutines concurrently: count(3) and count(2).
  • Both coroutines print their countdown values after a 1-second sleep.
  • The output will interleave as both coroutines run together.
  • The correct output, as shown in the screenshot, is:
    3
    2
    1
    1
    

Correct Option: 1

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: Which PySpark code splits each line of input using a comma as a separator?

  • To split each line using a comma in PySpark, use flatMap(lambda line: line.split(",")).
  • flatMap is used because split returns a list, and flatMap flattens the result.

Correct Option: flatMap(lambda line: line.split(","))

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of the given NumPy Python code using np.ix_ for advanced indexing?

  • The code uses np.ix_ to select rows 0 and 2, and columns 1 and 2 from the array.
  • The selected elements are:
  • From row 0: columns 1 and 2 β†’ [2, 3]
  • From row 2: columns 1 and 2 β†’ [8, 9]
  • The resulting array is:
    [[2 3]
    [8 9]]
    

Correct Option: 1

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What is the output of the given NumPy code using np.ix_ for advanced indexing?

  • The code selects rows 0 and 2, and columns 1 and 2 from the array.
  • The resulting subarray is:
    [[2 3]
    [8 9]]
    

Correct Option: 1

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: Perform Mann-Kendall Test on Trip_Total and calculate 95% confidence interval for Trip_Seconds.

  • For the Mann-Kendall Test on the Trip_Total column:
  • Calculate the test statistic and p-value (both to 2 decimals).
  • Determine the trend: "increasing" if statistic > 0, "decreasing" if < 0, "no trend" if 0.
  • Output format: [testStatistics_value, p_value, trend_of_data]
  • For the 95% confidence interval on Trip_Seconds:
  • Use the population standard deviation (ddof=0).
  • Output format: [lower_bound, upper_bound], both to 2 decimals.

πŸ”‘ Key Steps: - Read the dataset. - Use kendalltau or pyMannKendall for Mann-Kendall test. - Use numpy/pandas for mean and std, and scipy for confidence interval calculation.

πŸ’» Code:

import pandas as pd # Import pandas for data manipulation
import numpy as np # Import numpy for numerical operations
from scipy.stats import norm # Import norm for confidence interval calculation
import pymannkendall as mk # Import pymannkendall for Mann-Kendall test

# Load the dataset
df = pd.read_csv('input.csv') # Replace 'input.csv' with your dataset path

# 1.1 Mann-Kendall Test on Trip_Total
result = mk.original_test(df['Trip_Total']) # Perform Mann-Kendall test
test_stat = round(result.Tau, 2) # Get test statistic, round to 2 decimals
p_value = round(result.p, 2) # Get p-value, round to 2 decimals
if test_stat > 0:
 trend = "increasing" # Positive statistic means increasing trend
elif test_stat < 0:
 trend = "decreasing" # Negative statistic means decreasing trend
else:
 trend = "no trend" # Zero statistic means no trend
print([test_stat, p_value, trend]) # Output result

# 1.2 Confidence Interval on Trip_Seconds
data = df['Trip_Seconds'].dropna() # Remove NaN values
mean = data.mean() # Calculate mean
std = data.std(ddof=0) # Population standard deviation
n = len(data) # Sample size
z = norm.ppf(0.975) # 95% confidence, two-tailed
margin = z * std / np.sqrt(n) # Margin of error
lower = round(mean - margin, 2) # Lower bound, rounded
upper = round(mean + margin, 2) # Upper bound, rounded
print([lower, upper]) # Output confidence interval

πŸ’‘ Explanation: - Mann-Kendall test is a non-parametric test for trend detection in time series. - pymannkendall provides the test statistic (Tau) and p-value. - Confidence interval for the mean is calculated using the population standard deviation and the normal distribution (z-score for 95% is 1.96). - Outputs are formatted as required, rounded to 2 decimals. - Time complexity: O(n) for both calculations (single pass through data). - Space complexity: O(n) for storing the columns.

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: Calculate sample covariance between Trip_Miles and Fare columns (rounded to 2 decimal points).

  • Use pandas/numpy to calculate the sample covariance between the two columns.
  • Output should be a single float rounded to 2 decimals.

πŸ”‘ Key Steps: - Read the dataset. - Use pandas .cov() or numpy np.cov() with ddof=1 for sample covariance. - Extract the covariance value between Trip_Miles and Fare. - Round to 2 decimals and print.

πŸ’» Code:

import pandas as pd # Import pandas for data manipulation

# Load the dataset
df = pd.read_csv('dataset.csv') # Replace with the correct path if needed

# Calculate sample covariance between Trip_Miles and Fare
cov = df[['Trip_Miles', 'Fare']].cov().iloc[0, 1] # Get covariance value
cov_rounded = round(cov, 2) # Round to 2 decimals

print(cov_rounded) # Output the result

πŸ’‘ Explanation: - .cov() by default calculates sample covariance (ddof=1). - iloc[0, 1] extracts the covariance between Trip_Miles and Fare from the covariance matrix. - Time complexity: O(n), where n is the number of rows. - Space complexity: O(1) for the covariance calculation.

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What are the columns and their descriptions in the provided dataset?

  • The dataset contains the following columns:
  • Trip_ID: Unique identifier for each trip.
  • Trip_Start_Timestamp: Timestamp when the trip started (rounded to the nearest 15 minutes).
  • Trip_End_Timestamp: Timestamp when the trip ended (rounded to the nearest 15 minutes).
  • Trip_Seconds: Duration of the trip in seconds.
  • Trip_Miles: Distance of the trip in miles.
  • Pickup_Community_Area: Community area code where the trip started.
  • Dropoff_Community_Area: Community area code where the trip ended.
  • Fare: Fare for the trip.

  • You can proceed to launch the editor (Jupyter Notebook or Script) to start your analysis or coding tasks.

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What are the columns and their descriptions in the dataset for the data science assessment?

  • The dataset contains the following columns:
  • Trip_End_Timestamp: Timestamp when the trip ended (rounded to the nearest 15 minutes).
  • Trip_Seconds: Duration of the trip in seconds.
  • Trip_Miles: Distance of the trip in miles.
  • Pickup_Community_Area: Community area code where the trip started.
  • Dropoff_Community_Area: Community area code where the trip ended.
  • Fare: Fare for the trip.
  • Tips: Tip for the trip.
  • Tolls: Tolls for the trip.
  • Extras: Extra charges for the trip.
  • Trip_Total: Total cost of the trip.
  • Payment_Type: Type of payment method used.
  • Company: Taxi company name.

  • You can now proceed to launch the editor (Jupyter Notebook or Script) to start your analysis.

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What are the submission criteria and setup instructions for the Data Science Lead assessment on HackerEarth?

  • Write your code in the provided interface (Jupyter Notebook Python 3.10 or Script).
  • Submission must be a JSON file named submission.json.
  • The JSON file should match the format of sample_submission.json.
  • Each question is identified by a number (e.g., 1.1, 1.2, 1.3) as the key, with the answer as the value.
  • All numerical answers must be standard Python floats rounded to 2 decimal places (avoid explicit float() casting before rounding).
  • Your code will be evaluated in two phases:
  • Compile & Run: Evaluates against the public dataset.
  • Submit: Evaluates against the private/unseen dataset.
  • Once you select the editor and language, you cannot change it.
  • Click "Launch editor" to begin coding your solutions.

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What are the evaluation metrics, submission criteria, and setup instructions for the Data Science Lead test on HackerEarth?

  • Evaluation Metric: Uses Exact Match Scoring with Weighted Points. Your final score is the sum of predefined scores for all correct answers.
  • Submission Criteria:
  • Write your results (as a DataFrame) into a submission.json file.
  • The format must match the provided sample_submission.json.
  • Each answer should be keyed by question number (e.g., "1.1", "1.2").
  • All numerical answers must be standard Python floats rounded to 2 decimal places.
  • Setup Instructions:
  • Choose either Jupyter Notebook (Python 3.10) or Script as your editor.
  • Once selected, you cannot change the interface or programming language.
  • Access files in the code editor using:
    import pandas as pd
    dataset = pd.read_csv('dataset/dataset.csv')
    
  • Click "Launch editor" to begin coding your solutions.

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What are the setup instructions, supported languages, and evaluation/scoring criteria for the Data Science Lead assessment?

  • Setup Instructions:
  • Choose your editor: Jupyter Notebook (Python 3.10) or Script.
  • Once selected, you cannot change the interface or programming language.
  • Click "Launch editor" to begin.
  • Supported Languages:
  • Python 2, Python 3 (including 3.10 and 3.8), R (RScript).
  • File Reading:
  • Use the provided file reading guide for Python and R.
  • Submission:
  • For R: Use write_json(submission, "submission.json", pretty = TRUE) to save your results.
  • For Python: Save your results in a JSON file named submission.json matching the sample format.
  • Limits:
  • Time Limit: 15.0 seconds per input file.
  • Memory Limit: 256 MB.
  • Source Limit: 1024 KB.
  • Scoring:
  • Score is assigned if any testcase passes.
  • Your model is instantly evaluated on the sample dataset; final evaluation is on the full dataset after submission.
  • Your score may change after the final evaluation.

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What are the first three statistical analysis tasks required for the Data Science Lead assessment?

  • 1.1 – Mann-Kendall Test on Trip_Total column:
  • Calculate the test statistic (2 decimals) and p-value (2 decimals).
  • Determine the trend: "increasing" if statistic > 0, "decreasing" if < 0, "no trend" if 0.
  • Format: [testStatistics_value, p_value, trend_of_data]

  • 1.2 – Confidence Interval on Trip_Seconds column:

  • Calculate the lower and upper bounds of Trip_Seconds with a 95% confidence interval (2 decimals).
  • Use population standard deviation (ddof=0).
  • Format: [lower_bound, upper_bound]

  • 1.3 – Sample Covariance between Trip_Miles and Fare columns:

  • Calculate the sample covariance (2 decimals).
  • Format: sample covariance value

You should implement these calculations in your selected editor (Jupyter Notebook Python 3.10 or Script) and format your answers as specified for submission.

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What are the submission criteria and setup steps for the Data Science Lead assessment?

  • Write your code in the provided interface (Jupyter Notebook Python 3.10 or Script).
  • Submission file must be named submission.json and only in JSON format.
  • The format of your submission must match sample_submission.json.
  • Each question is identified by a number (e.g., 1.1, 1.2, 1.3) as the key, with the answer as the value.
  • All numerical answers must be standard Python floats rounded to 2 decimal places (avoid explicit float() casting before rounding).
  • Your code will be evaluated in two phases:
  • Compile & Run: Evaluates against the public dataset.
  • Submit: Evaluates against the private/unseen dataset.
  • Once you select the editor and language, you cannot change it.
  • Click "Launch editor" to begin coding your solutions.

interviewer is sharing their screen. Analyze the screen and provide a useful response. If there is technical/leetcode-style questions, follow the and the exactly.


Q: What are the first three statistical analysis tasks required for the Data Science Lead assessment, and what are their expected output formats?

  • 1.1 – Mann-Kendall Test on Trip_Total column
  • Calculate test statistic (2 decimals) and p-value (2 decimals).
  • Determine trend:
  • "increasing" if statistic > 0
  • "decreasing" if statistic < 0
  • "no trend" if statistic == 0
  • Format: [testStatistics_value, p_value, trend_of_data]

  • 1.2 – Confidence Interval on Trip_Seconds column

  • Calculate lower and upper bounds of Trip_Seconds with 95% confidence interval (2 decimals).
  • Use population standard deviation (ddof=0).
  • Format: [lower_bound, upper_bound]

  • 1.3 – Sample Covariance between Trip_Miles and Fare columns

  • Calculate sample covariance (2 decimals).
  • Format: sample covariance value

You should implement these calculations in your selected editor (Jupyter Notebook Python 3.10 or Script) and format your answers as specified for submission.

Direct Message from interviewee: write the code now


Q: Write code to solve the first three statistical analysis tasks: Mann-Kendall test, confidence interval, and sample covariance.

  • Use Python (pandas, numpy, scipy, pymannkendall) for calculations.
  • Read the dataset, perform each calculation, and format results as required.
  • Save results in submission.json matching the specified format.

πŸ”‘ Key Steps: - Read CSV data. - 1.1: Perform Mann-Kendall test on Trip_Total. - 1.2: Compute 95% confidence interval for Trip_Seconds (population std). - 1.3: Calculate sample covariance between Trip_Miles and Fare. - Round all results to 2 decimals. - Save output as JSON.

πŸ’» Code:

import pandas as pd # Import pandas for data manipulation
import numpy as np # Import numpy for numerical operations
import json # Import json for saving results
from scipy import stats # Import scipy.stats for confidence interval
import pymannkendall as mk # Import pymannkendall for Mann-Kendall test

# Read the dataset
df = pd.read_csv('dataset/dataset.csv') # Read the CSV file into a DataFrame

# 1.1 Mann-Kendall Test on Trip_Total
mk_result = mk.original_test(df['Trip_Total']) # Perform Mann-Kendall test
statistic = round(mk_result.Tau, 2) # Get and round the test statistic
p_value = round(mk_result.p, 2) # Get and round the p-value
if statistic > 0: # Determine trend
 trend = "increasing"
elif statistic < 0:
 trend = "decreasing"
else:
 trend = "no trend"
mann_kendall_output = [statistic, p_value, trend] # Prepare output

# 1.2 Confidence Interval on Trip_Seconds (population std)
data = df['Trip_Seconds'].dropna() # Remove NaNs
mean = data.mean() # Calculate mean
std = data.std(ddof=0) # Calculate population std
n = len(data) # Get sample size
z = 1.96 # Z-score for 95% confidence
margin = z * std / np.sqrt(n) # Calculate margin of error
lower = round(mean - margin, 2) # Lower bound
upper = round(mean + margin, 2) # Upper bound
confidence_interval_output = [lower, upper] # Prepare output

# 1.3 Sample Covariance between Trip_Miles and Fare
cov = np.cov(df['Trip_Miles'], df['Fare'], ddof=1)[0, 1] # Calculate sample covariance
cov_rounded = round(cov, 2) # Round to 2 decimals

# Prepare submission dictionary
submission = {
 "1.1": mann_kendall_output, # Mann-Kendall output
 "1.2": confidence_interval_output, # Confidence interval output
 "1.3": cov_rounded # Covariance output
}

# Save to submission.json
with open('submission.json', 'w') as f: # Open file for writing
 json.dump(submission, f) # Dump results as JSON

πŸ’‘ Explanation: - Mann-Kendall Test: Detects trend direction in Trip_Total using pymannkendall. Returns statistic, p-value, and trend label. - Confidence Interval: Uses population standard deviation (ddof=0) for Trip_Seconds and computes 95% CI with Z=1.96. - Sample Covariance: Uses numpy's cov with ddof=1 for unbiased sample covariance between Trip_Miles and Fare. - Output: All results are rounded to 2 decimals and saved in the required JSON format. - Complexity: All operations are linear in the number of rows (O(n)).


Q: How to perform the Mann-Kendall test for trend detection without the pymannkendall library (since it is not available in the environment)?

  • The error is due to the absence of the pymannkendall library in the environment.
  • You need to implement the Mann-Kendall test manually using only standard libraries (numpy, scipy, pandas).
  • Below is a simple implementation for the Mann-Kendall test that does not require external packages.

πŸ”‘ Key Steps: - Calculate the S statistic by comparing all pairs in the series. - Compute the variance of S. - Calculate the standardized Z statistic. - Compute the two-sided p-value using the normal distribution. - Determine the trend based on the sign of S.

πŸ’» Code:

import pandas as pd # Import pandas for data manipulation
import numpy as np # Import numpy for numerical operations
import json # Import json for saving results
from scipy.stats import norm # Import norm for p-value calculation

# Read the dataset
df = pd.read_csv('dataset/dataset.csv') # Read the CSV file into a DataFrame

# 1.1 Mann-Kendall Test on Trip_Total (manual implementation)
def mann_kendall_test(x):
 n = len(x) # Get the length of the series
 s = 0 # Initialize S statistic
 for k in range(n - 1): # Loop over all pairs
 for j in range(k + 1, n):
 s += np.sign(x[j] - x[k]) # Add sign of difference
 unique_x = np.unique(x) # Find unique values
 g = len(unique_x) # Number of unique values
 if n == g: # No ties
 var_s = (n * (n - 1) * (2 * n + 5)) / 18 # Variance formula without ties
 else: # With ties
 tp = np.array([np.sum(x == val) for val in unique_x]) # Tied group sizes
 var_s = (n * (n - 1) * (2 * n + 5) - np.sum(tp * (tp - 1) * (2 * tp + 5))) / 18 # Variance with ties
 if s > 0:
 z = (s - 1) / np.sqrt(var_s) # Z statistic for s > 0
 elif s < 0:
 z = (s + 1) / np.sqrt(var_s) # Z statistic for s < 0
 else:
 z = 0 # Z statistic for s == 0
 p = 2 * (1 - norm.cdf(abs(z))) # Two-sided p-value
 return round(z, 2), round(p, 2), "increasing" if s > 0 else "decreasing" if s < 0 else "no trend" # Return results

statistic, p_value, trend = mann_kendall_test(df['Trip_Total']) # Run test
mann_kendall_output = [statistic, p_value, trend] # Prepare output

# 1.2 Confidence Interval on Trip_Seconds (population std)
data = df['Trip_Seconds'].dropna() # Remove NaNs
mean = data.mean() # Calculate mean
std = data.std(ddof=0) # Population std
n = len(data) # Sample size
z = 1.96 # Z-score for 95% confidence
margin = z * std / np.sqrt(n) # Margin of error
lower = round(mean - margin, 2) # Lower bound
upper = round(mean + margin, 2) # Upper bound
confidence_interval_output = [lower, upper] # Prepare output

# 1.3 Sample Covariance between Trip_Miles and Fare
cov = np.cov(df['Trip_Miles'], df['Fare'], ddof=1)[0, 1] # Sample covariance
cov_rounded = round(cov, 2) # Round to 2 decimals

# Prepare submission dictionary
submission = {
 "1.1": mann_kendall_output, # Mann-Kendall output
 "1.2": confidence_interval_output, # Confidence interval output
 "1.3": cov_rounded # Covariance output
}

# Save to submission.json
with open('submission.json', 'w') as f: # Open file for writing
 json.dump(submission, f) # Dump results as JSON

πŸ’‘ Explanation: - This code manually implements the Mann-Kendall test, so it works even if pymannkendall is not available. - All other calculations remain unchanged and use only standard libraries. - Output is formatted as required for submission. - Time complexity for Mann-Kendall is O(n^2), but for typical dataset sizes this is acceptable.


Q: How to resolve KeyError: 'trip_seconds' when accessing DataFrame columns?

  • The error occurs because the DataFrame does not contain a column named 'trip_seconds'.
  • Check the actual column names in your CSV fileβ€”they are likely capitalized (e.g., 'Trip_Seconds').
  • Use print(df.columns) or logger.warning(df.columns) to inspect the column names.
  • Update your code to use the correct column name, matching the case exactly.

Corrected line:

data = df['Trip_Seconds'].dropna() # Use the correct column name as per your CSV

  • Make similar corrections for all column references (e.g., 'Trip_Miles', 'Fare', 'Trip_Total').
  • This will resolve the KeyError and allow your code to execute successfully.