開始使用免費開始

轉換數值資料

你是雜貨店的庫存分析師,需要計算庫存的總價值。你的資料包含商品數量與單價,但你需要把兩者結合,才能掌握庫存價值。由於數量以整數儲存,你需要先將它們轉換為 double,再與價格相乘。請計算每個商品的總價值,並建立新欄位來追蹤庫存投資。

已為你匯入 tablesaw 套件。

本練習屬於課程

使用 Java 進行資料清理

檢視課程

練習說明

  • 列印每個欄位的資料型別。
  • 將整數欄位 Stock_Quantity 轉換為 double 欄位。
  • quantity 乘以 unitPrice

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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());
            }
}
編輯並執行程式碼