Skip to content
Laviyx Learn

Try

NumPy and pandas Basics Practice

Practise NumPy arrays, creating and inspecting DataFrames, selecting, filtering, sorting and adding columns.

Beginner7 problemsUpdated

Review first: NumPy Arrays, Aggregations and Random Numbers, DataFrames, Selecting Data with loc and iloc, Filtering Rows, Sorting and Ranking

  1. 1.Exam score summary

    Beginner

    Given the scores [67, 82, 91, 58, 74, 88, 95, 61], use NumPy to print the mean (1 decimal), the median, the highest score and its position, and how many scores are 75 or more.

    Show hint

    np.array, .mean(), np.median, .max(), .argmax(), and (arr >= 75).sum().

    Show solution
    Python
    import numpy as np
    
    scores = np.array([67, 82, 91, 58, 74, 88, 95, 61])
    print(round(scores.mean(), 1), np.median(scores))
    print(scores.max(), scores.argmax())
    print((scores >= 75).sum())
    Output
    77.0 78.0
    95 6
    4
  2. 2.Prices with tax

    Beginner

    A 2 × 3 array holds prices of three products in two shops: [[100, 250, 80], [110, 240, 85]]. Add 18% GST to every price (rounded to 2 decimals) and print the cheapest shop for each product as 0 or 1.

    Show hint

    Multiply the whole array by 1.18. argmin(axis=0) gives the row with the smallest value in each column.

    Show solution
    Python
    import numpy as np
    
    prices = np.array([[100, 250, 80], [110, 240, 85]])
    with_gst = np.round(prices * 1.18, 2)
    print(with_gst)
    print(with_gst.argmin(axis=0))
    Output
    [[118.  295.   94.4]
     [129.8 283.2 100.3]]
    [0 1 0]
  3. 3.Build and inspect a DataFrame

    Beginner

    Create a DataFrame of five employees with columns name (Asha, Ravi, Meera, John, Priya), dept (Sales, IT, IT, HR, Sales) and salary (52000, 78000, 81000, 46000, 61000). Print its shape, the average salary, and the name of the highest earner.

    Show hint

    df.shape, df["salary"].mean(), and df.loc[df["salary"].idxmax(), "name"].

    Show solution
    Python
    import pandas as pd
    
    df = pd.DataFrame({
        "name": ["Asha", "Ravi", "Meera", "John", "Priya"],
        "dept": ["Sales", "IT", "IT", "HR", "Sales"],
        "salary": [52000, 78000, 81000, 46000, 61000],
    })
    print(df.shape)
    print(df["salary"].mean())
    print(df.loc[df["salary"].idxmax(), "name"])
    Output
    (5, 3)
    63600.0
    Meera
  4. 4.Filter and sort orders

    Beginner

    Orders have city = ["Mumbai", "Delhi", "Pune", "Delhi", "Mumbai", "Chennai"] and amount = [250, 700, 90, 320, 410, 150]. Print the orders over 200 from Mumbai or Delhi, sorted by amount from highest to lowest.

    Show hint

    isin(["Mumbai", "Delhi"]) combined with amount > 200 using &, then sort_values("amount", ascending=False).

    Show solution
    Python
    import pandas as pd
    
    orders = pd.DataFrame({
        "city": ["Mumbai", "Delhi", "Pune", "Delhi", "Mumbai", "Chennai"],
        "amount": [250, 700, 90, 320, 410, 150],
    })
    result = orders[orders["city"].isin(["Mumbai", "Delhi"]) & (orders["amount"] > 200)]
    print(result.sort_values("amount", ascending=False))
    Output
         city  amount
    1   Delhi     700
    4  Mumbai     410
    3   Delhi     320
    0  Mumbai     250
  5. 5.loc and iloc

    Beginner

    With names as the index of scores = pd.DataFrame({"maths": [92, 67, 78], "science": [88, 74, 81]}, index=["Asha", "Ravi", "Meera"]), print Ravi's science score with loc, the first row with iloc, and the maths column for the last two students using iloc.

    Show hint

    loc["Ravi", "science"], iloc[0], and iloc[1:, 0].

    Show solution
    Python
    import pandas as pd
    
    scores = pd.DataFrame({"maths": [92, 67, 78], "science": [88, 74, 81]}, index=["Asha", "Ravi", "Meera"])
    print(scores.loc["Ravi", "science"])
    print(scores.iloc[0])
    print(scores.iloc[1:, 0])
    Output
    74
    maths      92
    science    88
    Name: Asha, dtype: int64
    Ravi     67
    Meera    78
    Name: maths, dtype: int64
  6. 6.Totals and categories

    Beginner

    Items have price = [20, 60, 900, 350] and qty = [10, 5, 1, 2]. Add a total column and a size column that is "big" for totals of 500 or more and "small" otherwise, then print the table.

    Show hint

    df["total"] = df["price"] * df["qty"] and np.where(df["total"] >= 500, "big", "small").

    Show solution
    Python
    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame({"price": [20, 60, 900, 350], "qty": [10, 5, 1, 2]})
    df["total"] = df["price"] * df["qty"]
    df["size"] = np.where(df["total"] >= 500, "big", "small")
    print(df)
    Output
       price  qty  total   size
    0     20   10    200  small
    1     60    5    300  small
    2    900    1    900    big
    3    350    2    700    big
  7. 7.Counting categories

    Beginner

    Survey answers for preferred payment are ["upi", "card", "upi", "cash", "upi", "card", "upi"]. Print the count of each answer and each answer's share as a percentage (1 decimal).

    Show hint

    value_counts() and value_counts(normalize=True) * 100.

    Show solution
    Python
    import pandas as pd
    
    answers = pd.Series(["upi", "card", "upi", "cash", "upi", "card", "upi"])
    print(answers.value_counts())
    print((answers.value_counts(normalize=True) * 100).round(1))
    Output
    upi     4
    card    2
    cash    1
    Name: count, dtype: int64
    upi     57.1
    card    28.6
    cash    14.3
    Name: proportion, dtype: float64