使用 DataFrame 操作資料
套件安裝
安裝套件
1 | // 套件 Microsoft.Data.Analysis 檔案轉 DataFrame 格式 |
引用套件
1 | using System.IO; |
載入 CSV 資料
使用 LoadCsvFromString
1 | string csvfile = File.ReadAllText("test.csv"); |
建立測試資料
1 | Int32DataFrameColumn id = new Int32DataFrameColumn("ID", new int[] { 1, 2 }); |
輸出:
index | ID | Name | Age |
---|---|---|---|
0 | 1 | 張三 | 25 |
1 | 2 | 李四 |
加入新欄位
加入欄位 Height
1 | df.Columns.Add(new PrimitiveDataFrameColumn<int>("Height", new List<int>{180, 179})); |
輸出:
index | ID | Name | Age | Height |
---|---|---|---|---|
0 | 1 | 張三 | 25 | 180 |
1 | 2 | 李四 | 179 |
顯示欄位資訊
了解欄位類型與資料筆數統計
1 | df.Info().Display(); |
輸出:
index | Info | ID | Name | Age | Height |
---|---|---|---|---|---|
0 | DataType | System.Int32 | System.String | System.Int32 | System.Int32 |
1 | Length(excluding null values) | 2 | 2 | 1 | 2 |
回傳統計摘要
統計相關值,此欄為數值欄位限定
1 | df.Description().Display(); |
輸出:
index | Description | ID | Age | Height |
---|---|---|---|---|
0 | Length (excluding null values) | 2 | 1 | 2 |
1 | Max | 2 | 25 | 180 |
2 | Min | 1 | 25 | 179 |
3 | Mean | 1.5 | 12.5 | 179.5 |
回傳前 N 筆資料
1 | df.Head(1).Display(); |
輸出:
index | ID | Name | Age | Height |
---|---|---|---|---|
0 | 1 | 張三 | 25 | 180 |
回傳後 N 筆資料
1 | df.Tail(1).Display(); |
輸出:
index | ID | Name | Age | Height |
---|---|---|---|---|
0 | 2 | 李四 | 179 |
加入新資料
填入每一欄對應資料
1 | df.Append(new List<KeyValuePair<string, object>>() { |
輸出:
index | ID | Name | Age | Height |
---|---|---|---|---|
0 | 1 | 張三 | 25 | 180 |
1 | 2 | 李四 | 179 | |
2 | 3 | 王五 | 20 | 170 |
缺失值處理
針對表格中的缺失欄位做處理
- 排除有空值的欄位
1 | DataFrame dropNullData = df.DropNulls(); |
輸出:
index | ID | Name | Age | Height |
---|---|---|---|---|
0 | 1 | 張三 | 25 | 180 |
1 | 3 | 王五 | 20 | 170 |
- 缺失值填充
1 | df.Columns["Age"] = df.Columns["Age"].FillNulls(0); |
輸出:
index | ID | Name | Age | Height |
---|---|---|---|---|
0 | 1 | 張三 | 25 | 180 |
1 | 2 | 李四 | 0 | 179 |
2 | 3 | 王五 | 20 | 170 |
排序資料
1 | DataFrame orderByData = df.OrderByDescending("Age"); |
輸出:
index | ID | Name | Age | Height |
---|---|---|---|---|
0 | 1 | 張三 | 25 | 180 |
1 | 3 | 王五 | 20 | 170 |
2 | 2 | 李四 | 0 | 179 |
分群資料
1 | DataFrame groupByData = df.GroupBy("Age").Count(); |
輸出:
index | Age | ID | Name | Height |
---|---|---|---|---|
0 | 25 | 1 | 1 | 1 |
1 | 0 | 1 | 1 | 1 |
2 | 20 | 1 | 1 | 1 |
篩選資料
1 | DataFrame filterData = df.Filter(df.Columns["Age"].ElementwiseGreaterThan(1)); |
輸出:
index | ID | Name | Age | Height |
---|---|---|---|---|
0 | 1 | 張三 | 25 | 180 |
1 | 3 | 王五 | 20 | 170 |
合併資料
1 | // 建立新的列表 |
輸出:
index | ID_left | Weight | ID_right | Name | Age | Height |
---|---|---|---|---|---|---|
0 | 1 | 60 | 1 | 張三 | 25 | 180 |
1 | 2 | 90 | 2 | 李四 | 0 | 179 |
📜 參考資料