Java 数据清洗
Dennis Lee
Software Engineer
| Books | Authors | Language | First_Published | Sales_in_Millions | Average_Price |
|---|---|---|---|---|---|
| A Tale of Two Cities | Charles Dickens | English | 1859 | 200.0 | 12.99 |
| The Little Prince (Le Petit Prince) | Antoine de Saint-Exupéry | French | 1943 | 200.0 | 15.50 |
| Harry Potter and the Philosopher's Stone | J. K. Rowling | English | 1997 | 120.0 | 19.99 |
| And Then There Were None | Agatha Christie | English | 1939 | 100.0 | 14.95 |
import tech.tablesaw.api.Table;
import tech.tablesaw.api.DoubleColumn;
import tech.tablesaw.api.StringColumn;
// 将 CSV 加载为 Tablesaw 表
Table books = Table.read().csv("bestsellers.csv");
// 基本信息:行数、列数、列名
System.out.println("行数:" + books.rowCount());
System.out.println("列数:" + books.columnCount());
System.out.println("列名:" + books.columnNames());
行数:290
列数:6
列名:[Books, Authors, Language, First_Published, Sales_in_millions]
for (String columnName : books.columnNames()) {// 按列名获取列,并统计该列的缺失值(null) int missing = books.column(columnName).countMissing();System.out.println(columnName + " 缺失值:" + missing); }
Books 缺失值:0
Authors 缺失值:0
Language 缺失值:0
First_Published 缺失值:0
Sales_in_millions 缺失值:2
Average_Price 缺失值:0
// countBy() 创建包含唯一值及其频数的新表
Table languageCounts = books.countBy("Language");
System.out.println("语言分布:\n");
// 打印格式化表,显示每种语言及其计数
System.out.println(languageCounts);
语言分布:
| 语言 | 计数 |
|------|------|
| English | 210 |
| French | 10 |
| Chinese | 6 |
| Portuguese | 1 |
| Spanish | 3 |
| German | 6 |
| Italian | 5 |
// 以 DoubleColumn 获取数值列,便于统计运算 DoubleColumn sales = books.doubleColumn("Sales_in_millions");System.out.println("销售统计(百万册):\n"); // 列中最小值 System.out.println("最小销量:" + sales.min() + " 百万"); // 列中最大值 System.out.println("最大销量:" + sales.max() + " 百万");// 全部数值的平均值 System.out.println("平均销量:" + sales.mean() + " 百万"); // 离散程度(标准差) System.out.println("标准差:" + sales.standardDeviation() + " 百万");
销售统计(百万册):
最小销量:10.0 百万
最大销量:600.0 百万
平均销量:49.996875 百万
标准差:64.6846320839116 百万
System.out.printf("行数:%d,列数:%s", books.rowCount(), books.columnCount());
for (String colName : books.columnNames()) // 遍历各列
System.out.println(books.column(colName).countMissing()); // 统计空值
StringColumn language = books.stringColumn("Language"); // 获取文本列
Table langCounts = books.countBy("Language"); // 统计类别频数
// 计算数值统计量
DoubleColumn sales = books.doubleColumn("Sales_in_Millions"); // 获取数值列
System.out.printf("均值:%.1f 百万,最小值:%.1f 百万,最大值:%.1f 百万",
sales.mean(), sales.min(), sales.max());
行数:290,列数:6
Books 缺失值:0
Authors 缺失值:0
| 语言 | 计数 |
|------|------|
| English | 210 |
| French | 10 |
均值:50.0 百万,最小值:10.0 百万,最大值:600.0 百万
Java 数据清洗