CommencerCommencer gratuitement

Transforming numeric data

As an inventory analyst at a grocery store, you need to calculate the total value of your stock. Your data shows product quantities and unit prices, but you need to combine these to understand inventory worth. Since quantities are stored as integers, you'll need to convert them to doubles before multiplying with prices. Calculate each product's total value, creating a new column to track inventory investment.

tablesaw packages have been imported for you.

Cet exercice fait partie du cours

Cleaning Data in Java

Afficher le cours

Instructions

  • Print the data type of each column.
  • Convert the integer column Stock_Quantity to a double column.
  • Multiply quantity by unitPrice.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

public class GroceryDataTransformation {
    public static void main(String[] args) {
        Table inventory = Table.read().csv("grocery_inventory.csv");

        System.out.println("Column datatypes:");
        for (String columnName : inventory.columnNames()) {
            // Print the data type of each column
            System.out.println(columnName + ": " + inventory.____(columnName).____());
        }

        // Convert the integer column to a double column
        DoubleColumn quantity = inventory.____("Stock_Quantity").____();
        DoubleColumn unitPrice = inventory.doubleColumn("Unit_Price");

        // Multiply the quantity by the unit price
        DoubleColumn totalValue = ____.____(unitPrice)
                .setName("Total_Value");
        inventory.addColumns(totalValue);

        System.out.println("\nMultiplying two columns: Stock_Quantity * Unit_Price = Total_Value");
        System.out.println(inventory.selectColumns("Product_Name", "Stock_Quantity", "Unit_Price", "Total_Value")
                .first(4).print());
            }
}
Modifier et exécuter le code