我正在嘗試對資料集進行資料清理。通過資料清理,我的意思是洗掉包含NaN或重復值或空單元格的行。這是我的代碼
資料集如下所示:
Sno Country noofDeaths
1 32432
2 Pakistan NaN
3 USA 3332
3 USA 3332
excel檔案圖片:

public class data_reader {
String filePath="src\\abc.csv";
public void readData() {
BufferedReader br = null;
String line = "";
HashSet<String> lines = new HashSet<>();
try {
br = new BufferedReader(new FileReader(filePath));
while ((line = br.readLine()) != null) {
if(!line.contains("NaN") || !line.contains("")) {
if (lines.add(line)) {
System.out.println(line);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
它適用于 NaN 值和重復行,但不適用于空單元格,請幫助如何做到這一點。
!line.contains("")
這是行不通的。
uj5u.com熱心網友回復:
條件!line.contains("") - 沒有意義,因為每個字串都包含空字串。
一般建議:
- 不要硬編碼檔案路徑,代碼必須是可重用的;
- 使用資源嘗試;
- 駝峰式名稱。
public class DataReader {
public static void main(String[] args) {
new DataReader().readData("src\\abc.csv");
}
public void readData(String filePath) {
try(BufferedReader br = new BufferedReader(new FileReader(filePath))) {
HashSet<String> lines = new HashSet<>();
String line = null;
while ((line = br.readLine()) != null) {
if(!line.contains("NaN")) {
for (String cell: line.split(",")) {
if (!cell.isBlank()&&lines.add(cell)) {
System.out.print(cell " ");
}
}
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
uj5u.com熱心網友回復:
在我看來,這是一個很容易解決的問題。給定一個空行的 CSV 檔案
foo,bar,baz
1,One,123
,,
2,Two,456
3,Three,789
您可以閱讀這些行并將空行定義為包含用逗號分隔的空字串的行。您可以讀取檔案的內容,將填充的行存盤到字串緩沖區中,然后在提取空行后保存緩沖區的內容。下面的代碼實作了這一點:
public static void main(String[] args) throws IOException {
String file ="test.csv";
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
StringBuilder sbuff = new StringBuilder();
while ((line = reader.readLine()) != null) {
String[] tokens = line.split(",");
if (containsText(tokens)) {
sbuff.append(line "\n");
}
}
reader.close();
System.out.println(sbuff.toString());
// save file here
}
public static boolean containsText(String[] tokens) {
for (String token: tokens) {
if (token.length() > 0)
return true;
}
return false;
}
運行代碼后,輸出為:
foo,bar,baz
1,One,123
2,Two,456
3,Three,789
相同的代碼可用于通過簡單的方法確定單元格是否為空:
public static boolean isCellEmpty(String[] tokens) {
for (String token: tokens) {
if (token.isBlank())
return true;
}
return false;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/418858.html
標籤:
