Excel 数据修复:使用 KNN 算法填充缺失值
Excel 数据修复:使用 KNN 算法填充缺失值
本文将介绍如何使用 Java 和 Apache POI 库,利用 KNN 算法填充 Excel 数据中的缺失值。
代码示例
// 导入必要的库
package 数据修复;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class knn01 {
public static void main(String[] args) {
// 定义输入文件和输出文件的路径
String inputFile = "input.xlsx";
try (Workbook workbook = WorkbookFactory.create(new FileInputStream(inputFile))) { // 使用工作簿工厂创建 Excel 工作簿
Sheet sheet = workbook.getSheetAt(0); // 获取 Excel 工作表
DecimalFormat df = new DecimalFormat("#.##"); // 创建 Decimal 格式化器,用于保留两位小数
// 对每一行进行处理
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i); // 获取行对象
if (row != null) {
Cell cell = row.getCell(1); // 获取第二列单元格
if (cell != null && cell.getCellType() != CellType.BLANK) {
// 如果单元格不为空,则跳过
} else {
double avg = calculateKNN(sheet, i, 1); // 计算KNN邻近算法填充的值
if (avg > 0) { // 如果填充的值大于 0
if(cell == null){
cell = row.createCell(1);
}
cell.setCellValue(Double.parseDouble(df.format(avg))); // 将填充的值填入单元格
}
}
}
}
// 创建新的工作表
String newSheetName = "数据补";
int sheetIndex = workbook.getSheetIndex(newSheetName);
Sheet newDataSheet;
if (sheetIndex >= 0) {
newDataSheet = workbook.getSheetAt(sheetIndex);
workbook.removeSheetAt(sheetIndex);
} else {
newDataSheet = workbook.createSheet(newSheetName);
}
// 复制原工作表的数据到新的工作表
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
Row oldRow = sheet.getRow(i);
Row newRow = newDataSheet.createRow(i);
if (oldRow != null) {
for (int j = 0; j < oldRow.getLastCellNum(); j++) {
Cell oldCell = oldRow.getCell(j);
Cell newCell = newRow.createCell(j);
if (oldCell != null) {
if(oldCell.getCellType() == CellType.STRING){
newCell.setCellValue(oldCell.getStringCellValue());
} else if(oldCell.getCellType() == CellType.NUMERIC){
newCell.setCellValue(oldCell.getNumericCellValue());
} else if(oldCell.getCellType() == CellType.BOOLEAN){
newCell.setCellValue(oldCell.getBooleanCellValue());
} else if(oldCell.getCellType() == CellType.FORMULA){
newCell.setCellValue(oldCell.getCellFormula());
} else if(oldCell.getCellType() == CellType.ERROR){
newCell.setCellValue(oldCell.getErrorCellValue());
}
}
}
}
}
// 将工作簿写入输入文件
FileOutputStream outputStream = new FileOutputStream(inputFile);
workbook.write(outputStream);
outputStream.close();
System.out.println("Data filling completed."); // 输出信息
} catch (Exception e) { // 捕获异常
e.printStackTrace();
}
}
// 计算KNN邻近算法填充的值
private static double calculateKNN(Sheet sheet, int rowIndex, int columnIndex) {
List<Double> data = new ArrayList<Double>(); // 存储数据
for (int i = 0; i <= sheet.getLastRowNum(); i++) { // 对每一行进行处理
Row row = sheet.getRow(i); // 获取行对象
if (row != null) {
Cell cell = row.getCell(columnIndex); // 获取指定列的单元格
if (cell != null && cell.getCellType() == CellType.NUMERIC) {
data.add(cell.getNumericCellValue()); // 将数据添加到列表中
}
}
}
if (data.size() > 0) { // 如果存在数据
double missingValue = 0; // 缺失值
Row row = sheet.getRow(rowIndex); // 获取当前行对象
if (row != null) {
Cell cell = row.getCell(columnIndex); // 获取指定列的单元格
if (cell == null || cell.getCellType() == CellType.BLANK) { // 如果单元格为空
missingValue = 0; // 缺失值为 0
} else if (cell.getCellType() == CellType.NUMERIC) {
missingValue = cell.getNumericCellValue(); // 缺失值为单元格中的值
} else if (cell.getCellType() == CellType.STRING) {
try {
missingValue = Double.parseDouble(cell.getStringCellValue()); // 转换为数字类型
} catch (NumberFormatException e) {
missingValue = 0; // 转换失败则缺失值为 0
}
}
}
if (missingValue > 0) { // 如果缺失值大于 0
return missingValue; // 直接返回缺失值
} else {
List<Double> distances = new ArrayList<Double>(); // 存储距离
for (double value : data) { // 遍历数据
double distance = Math.abs(value - missingValue); // 计算距离
distances.add(distance); // 将距离添加到列表中
}
Collections.sort(distances, new Comparator<Double>() { // 对距离进行排序
@Override
public int compare(Double o1, Double o2) {
return Double.compare(o1, o2);
}
});
int k = 3; // 取前三个最近的邻居
double sum = 0; // 总和
int count = 0; // 计数器
for (int i = 0; i < k && i < distances.size(); i++) { // 对前 k 个最近的邻居进行处理
double value = data.get(distances.indexOf(distances.get(i))); // 获取对应的值
sum += value; // 累加值
count++; // 计数器加 1
}
if (count > 0) { // 如果计数器大于 0
return sum / count; // 返回平均值
} else {
return 0; // 否则返回 0
}
}
} else {
return 0; // 如果不存在数据,则返回 0
}
}
// 解析日期
private static Date parseDate(String dateString) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // 创建日期格式化器
try {
return dateFormat.parse(dateString); // 解析日期
} catch (ParseException e) { // 捕获异常
e.printStackTrace();
return null; // 返回 null
}
}
}
代码说明
- 导入必要的库:导入 Apache POI 库和一些 Java 库,例如
FileInputStream、FileOutputStream等。 - 创建工作簿:使用
WorkbookFactory.create()方法从输入文件创建 Excel 工作簿。 - 获取工作表:使用
workbook.getSheetAt(0)方法获取第一个工作表。 - 创建新的工作表:使用
workbook.createSheet(newSheetName)方法创建一个名为“数据补”的新工作表。 - 复制数据:将原工作表的数据复制到新的工作表。
- 填充缺失值:
- 遍历工作表的每一行,检查第二列的单元格是否为空。
- 如果为空,调用
calculateKNN()方法计算 KNN 填充值。 - 将计算得到的填充值写入单元格。
- 保存工作簿:使用
workbook.write()方法将修改后的工作簿写入输入文件。
KNN 算法填充值的计算
calculateKNN() 方法实现 KNN 算法,计算缺失值的填充值。
- 获取数据:从工作表的指定列获取所有非空数据。
- 获取缺失值:从当前行获取指定列的单元格值,如果为空,则缺失值为 0。
- 计算距离:遍历所有数据,计算每个数据与缺失值的距离。
- 排序:对距离进行排序。
- 取前 k 个最近邻居:取前 k 个最近邻居的对应值,k 通常设置为 3。
- 计算平均值:计算前 k 个最近邻居的平均值作为缺失值的填充值。
总结
本文介绍了如何使用 Java 和 Apache POI 库,利用 KNN 算法填充 Excel 数据中的缺失值。代码示例展示了如何读取 Excel 文件、计算 KNN 邻近值并写入新的工作表。
希望这篇文章对您有所帮助。
原文地址: https://www.cveoy.top/t/topic/fweg 著作权归作者所有。请勿转载和采集!