0% found this document useful (0 votes)
93 views2 pages

NumPy and Pandas Practice Questions

Uploaded by

OMKAR AGARWAL
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views2 pages

NumPy and Pandas Practice Questions

Uploaded by

OMKAR AGARWAL
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Pandas and NumPy Exam Practice Questions

NumPy Practice Questions


1. Array Creation and Manipulation:
- Create a 3x3 array filled with random integers between 10 and 50.
- Replace all even numbers in the array with -1.
- Reshape the array into a 1D array.

2. Matrix Operations:
- Create two 3x3 matrices A and B using NumPy with random values between 1 and 10.
- Compute their matrix product A × B.
- Find the transpose of the result and its determinant.

3. Indexing and Slicing:


- Create a 5x5 matrix with values from 1 to 25.
- Extract the middle 3x3 submatrix.
- Set all values in the last column to 0.

4. Statistical Analysis:
- Create an array of 50 random numbers between 0 and 100.
- Find the mean, median, standard deviation, and variance of the array.
- Sort the array in descending order.

5. Broadcasting:
- Create a 3x3 matrix and a 3x1 column vector.
- Add the column vector to each row of the matrix using broadcasting.

Pandas Practice Questions


1. DataFrame Creation and Basic Operations:
- Create a DataFrame from the following dictionary:
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'Salary': [50000, 60000, 70000, 80000]
}
- Add a new column 'Tax' which is 10% of the Salary.
- Drop rows where the 'Age' is greater than 30.

2. Filtering and Indexing:


- Load a CSV file (or create one if not available) containing columns like Product, Price, and
Quantity.
- Filter all rows where Price > 100.
- Find the total quantity of all products with Price > 100.
3. Aggregation and Grouping:
- Create a DataFrame with columns ['Department', 'Employee', 'Salary'].
- Group the data by 'Department' and calculate the total salary for each department.
- Find the average salary of employees in each department.

4. Handling Missing Data:


- Create a DataFrame with some missing values:
df = [Link]({
'A': [1, 2, None, 4],
'B': [None, 2, 3, 4],
'C': [1, 2, 3, None]
})
- Fill missing values in column 'A' with the mean of that column.
- Drop rows where more than one value is missing.

5. Merging and Joining:


- Create two DataFrames:
df1 = [Link]({'ID': [1, 2, 3], 'Name': ['Alice', 'Bob', 'Charlie']})
df2 = [Link]({'ID': [1, 2, 4], 'Age': [25, 30, 35]})
- Merge them on 'ID' using an inner join.
- Perform a left join and explain the difference.

6. Time Series Analysis:


- Create a DataFrame with a 'Date' column containing dates from January 1, 2023, to
January 31, 2023.
- Add a column 'Sales' with random values.
- Find the total sales for the first week of January.

Combined NumPy and Pandas Questions


1. Data Transformation:
- Use NumPy to create an array of 100 random integers between 1 and 100.
- Convert it into a Pandas DataFrame with columns ['Value'].
- Add a new column 'Category' where:
- 'Low' if the value is < 30.
- 'Medium' if the value is between 30 and 70.
- 'High' if the value is > 70.

2. Statistical Analysis:
- Create a large DataFrame with 10,000 rows and 5 columns containing random integers.
- Use NumPy to compute the correlation matrix.
- Use Pandas to identify columns with the highest correlation.

3. Performance Comparison:
- Create a NumPy array and a Pandas DataFrame, both with 1,000,000 random values.
- Compare the time taken to compute the mean of both using NumPy and Pandas.

Common questions

Powered by AI

Pandas provides efficient methods for handling missing data, such as fillna() to replace NaNs with specific values or dropna() to remove records depending on data completeness. This automates data cleaning, reducing errors and saving time compared to manual approaches, which are prone to oversight and inconsistencies. Pandas' approach enhances data reliability and integrity, vital for accurate analysis .

To compute the correlation matrix of a large DataFrame, use the corr() method in Pandas, which provides pairwise correlation of columns. NumPy can be used for computational efficiency. Identifying highly correlated columns is crucial as it reveals relationships within the data, which can be significant in predictive modeling and feature selection. High correlation between features suggests redundancy, which can simplify models without losing information .

Aggregation and grouping in Pandas involve using functions like groupby() which organizes data into categories followed by computation like sum(), mean() on these groups. This approach summarizes large datasets, revealing patterns, such as total or average values per category, enabling strategic decisions based on departmental performance or market segmentation insights .

NumPy arrays tend to offer higher performance for operations like computing the mean due to lower overhead; they are closer to raw data and generally faster. Pandas DataFrames provide more functionality but at the cost of additional layers of abstraction, impacting speed. Evaluating performance differences guides choosing efficient data structures in large-scale data analytics, with NumPy preferred for performance-critical tasks and Pandas for complex data manipulations .

To create a 3x3 array filled with random integers between 10 and 50 in NumPy, you can use np.random.randint(10, 50, (3, 3)). This array can then be reshaped into a 1D array using the reshape method, like array.reshape(9). A practical application could be preparing data for machine learning where reshaped 1D arrays are required for input into certain types of models .

NumPy can generate an array of random integers using np.random.randint, which can then be transformed into a Pandas DataFrame. Using DataFrame methods, a new column can categorize values as 'Low', 'Medium', or 'High' based on their range. This transformation serves various purposes, such as preparing data for categorical analyses or machine learning models, where numerical ranges are grouped into clusters to improve interpretability or feature extraction .

Analyzing a 50-element array with statistical functions such as mean, median, standard deviation, and variance provides insights into the dataset's central tendency and spread. The mean gives the average value, showing the center of the data distribution. The median offers insight into the middle value, useful when the data contains outliers. The standard deviation and variance inform about data spread; high values indicate data widely spread around the mean, while low values suggest data closely clustered. These insights help in understanding variability, guiding decisions in fields like finance or quality control .

To calculate total sales for a specific period using Pandas, filter the DataFrame for dates within the desired range, then apply the sum() function on the sales column. This analysis is crucial for understanding trends, making informed business decisions, forecasting demand, and managing inventory effectively, ensuring operations align with consumer behavior patterns .

Merging two DataFrames on a common column involves combining data based on matching column values. An inner join returns only the rows with matching values in both DataFrames, thus maintaining only the intersection of the datasets. A left join returns all rows from the left DataFrame and the matched rows from the right DataFrame, filling with NaNs where no match is found. This approach is useful for retaining all data from the primary dataset while integrating available details from the secondary dataset .

Broadcasting in NumPy allows for arrays of different shapes to be combined in arithmetic operations. When adding a 3x1 column vector to each row of a 3x3 matrix, NumPy automatically expands the dimensions of the smaller array across the larger one, so that each element in the column vector is added to the corresponding element in each row of the matrix. The result is a new 3x3 matrix where each row is the sum of the original row and the column vector .

You might also like