.NET 幫助

Deedle C#(如何為開發人員工作)

發佈 2024年7月1日
分享:

Deedle C

Deedle 是一個強大的數據操作和數據分析庫。它提供完整的數據框和系列,允許您高效處理結構化數據框。Deedle 提供處理缺失數據、對齊數據和應用靜態成員 ofNullablesofObservations 的輔助函數的工具。由於其靈活性和性能,它在數據科學中被廣泛應用。

IronPDF 是一個用於在 .NET 中創建和處理 PDF 文件的庫。它幫助您從 HTML 生成 PDF、將圖像轉換為 PDF 並從 PDF 文件中提取內容。IronPDF 簡化了您在 .NET 項目中的 PDF 任務。

在本文中,您將學習如何開始使用 Deedle for C#,並使用 Visual Studio 在您的 .NET 項目中設置它,並實現具有自動生成文檔的關鍵功能。您將看到代碼示例和解釋,幫助您理解如何有效地使用 Deedle,包括如何應用指定的功能。

開始使用 Deedle C

在 .NET 專案中設定 Deedle

開始時,在 Visual Studio要在您的 .NET 專案中使用 Deedle,您需要安裝 Deedle NuGet 套件。請在 NuGet 控制台中執行以下命令:

Install-Package Deedle

安裝後,您需要將 Deedle 命名空間導入您的專案:

using Deedle;
using Deedle;
Imports Deedle
VB   C#

基本範例代碼

讓我們從一個基本範例開始,來創建和操作一個數據框架。這將幫助你了解Deedle的基礎知識。

using System;
using Deedle;
class Program
{
    static void Main()
    {
        // Creating a series
        var series = new Series<int, double>(new[] { 1, 2, 3 }, new[] { 3.5, 4.2, 5.1 });
        Console.WriteLine("Series:");
        Console.WriteLine(series);

        // Creating a data frame
        var rowIndex = new[] { 1, 2, 3 };
        var colIndex = new[] { "A", "B" };
        var data = new double[,] { { 1.0, 3.5 }, { 2.0, 4.2 }, { 3.0, 5.1 } };
        var dataFrame = Frame.FromArray2D(data)
                             .IndexRowsWith(rowIndex)
                             .IndexColumnsWith(colIndex);
        Console.WriteLine("Data Frame:");
        Console.WriteLine(dataFrame);
    }
}
using System;
using Deedle;
class Program
{
    static void Main()
    {
        // Creating a series
        var series = new Series<int, double>(new[] { 1, 2, 3 }, new[] { 3.5, 4.2, 5.1 });
        Console.WriteLine("Series:");
        Console.WriteLine(series);

        // Creating a data frame
        var rowIndex = new[] { 1, 2, 3 };
        var colIndex = new[] { "A", "B" };
        var data = new double[,] { { 1.0, 3.5 }, { 2.0, 4.2 }, { 3.0, 5.1 } };
        var dataFrame = Frame.FromArray2D(data)
                             .IndexRowsWith(rowIndex)
                             .IndexColumnsWith(colIndex);
        Console.WriteLine("Data Frame:");
        Console.WriteLine(dataFrame);
    }
}
Imports System
Imports Deedle
Friend Class Program
	Shared Sub Main()
		' Creating a series
		Dim series As New Series(Of Integer, Double)( { 1, 2, 3 }, { 3.5, 4.2, 5.1 })
		Console.WriteLine("Series:")
		Console.WriteLine(series)

		' Creating a data frame
		Dim rowIndex = { 1, 2, 3 }
		Dim colIndex = { "A", "B" }
		Dim data = New Double(, ) {
			{ 1.0, 3.5 },
			{ 2.0, 4.2 },
			{ 3.0, 5.1 }
		}
		Dim dataFrame = Frame.FromArray2D(data).IndexRowsWith(rowIndex).IndexColumnsWith(colIndex)
		Console.WriteLine("Data Frame:")
		Console.WriteLine(dataFrame)
	End Sub
End Class
VB   C#

在此範例中,您使用整數型的列鍵和雙精度值創建一個序列。然後,您使用雙精度值的二維陣列創建一個數據框。您使用整數索引行並使用字串索引列。

實現 Deedle C# 的功能

處理缺失值

處理缺失值在資料操作中是至關重要的。Deedle 提供了對缺失資料的強大支持。您可以創建包含缺失值的序列並執行操作來處理它們。

using System;
using Deedle;
class Program
{
    static void Main()
    {
        var series = new Series<int, double?>(
            new[] { 75, 8, 47, 5 },
            new double?[] { 75.0, null, 47.0, 5.0 }
        );
        Console.WriteLine("Original Series with Missing Values:");
        Console.WriteLine(series);

        // Fill missing values with a specified value
        var filledSeries = series.FillMissing(0.0);
        Console.WriteLine("Series after Filling Missing Values:");
        Console.WriteLine(filledSeries);
    }
}
using System;
using Deedle;
class Program
{
    static void Main()
    {
        var series = new Series<int, double?>(
            new[] { 75, 8, 47, 5 },
            new double?[] { 75.0, null, 47.0, 5.0 }
        );
        Console.WriteLine("Original Series with Missing Values:");
        Console.WriteLine(series);

        // Fill missing values with a specified value
        var filledSeries = series.FillMissing(0.0);
        Console.WriteLine("Series after Filling Missing Values:");
        Console.WriteLine(filledSeries);
    }
}
Imports System
Imports Deedle
Friend Class Program
	Shared Sub Main()
		Dim series As New Series(Of Integer, Double?)( { 75, 8, 47, 5 }, New Double?() { 75.0, Nothing, 47.0, 5.0 })
		Console.WriteLine("Original Series with Missing Values:")
		Console.WriteLine(series)

		' Fill missing values with a specified value
		Dim filledSeries = series.FillMissing(0.0)
		Console.WriteLine("Series after Filling Missing Values:")
		Console.WriteLine(filledSeries)
	End Sub
End Class
VB   C#

此範例創建了一個包含缺失值的序列,並用指定值填充它們。您也可以使用靜態成員方法,如 ofOptionalObservationsofValues,以應對更複雜的情境。

資料操作

Deedle 允許您執行各種資料操作任務。您可以在資料框中過濾、轉換和聚合資料。

using System;
using Deedle;
class Program
{
    static void Main()
    {
        var rowIndex = new[] { 1, 2, 3 };
        var colIndex = new[] { "A", "B" };
        var data = new double[,] { { 1.0, 3.5 }, { 2.0, 4.2 }, { 3.0, 5.1 } };
        var dataFrame = Frame.FromArray2D(data)
                             .IndexRowsWith(rowIndex)
                             .IndexColumnsWith(colIndex);
        Console.WriteLine("Original Data Frame:");
        Console.WriteLine(dataFrame);

        // Filter rows where column 'A' is greater than 1.5
        var filteredFrame = dataFrame.Where(row => row.Value.GetAs<double>("A") > 1.5);
        Console.WriteLine("Filtered Data Frame:");
        Console.WriteLine(filteredFrame);

        dataFrame.AddColumn("C", dataFrame["A"] + dataFrame["B"]);
        Console.WriteLine("Transformed Data Frame with New Column 'C':");
        Console.WriteLine(dataFrame);
    }
}
using System;
using Deedle;
class Program
{
    static void Main()
    {
        var rowIndex = new[] { 1, 2, 3 };
        var colIndex = new[] { "A", "B" };
        var data = new double[,] { { 1.0, 3.5 }, { 2.0, 4.2 }, { 3.0, 5.1 } };
        var dataFrame = Frame.FromArray2D(data)
                             .IndexRowsWith(rowIndex)
                             .IndexColumnsWith(colIndex);
        Console.WriteLine("Original Data Frame:");
        Console.WriteLine(dataFrame);

        // Filter rows where column 'A' is greater than 1.5
        var filteredFrame = dataFrame.Where(row => row.Value.GetAs<double>("A") > 1.5);
        Console.WriteLine("Filtered Data Frame:");
        Console.WriteLine(filteredFrame);

        dataFrame.AddColumn("C", dataFrame["A"] + dataFrame["B"]);
        Console.WriteLine("Transformed Data Frame with New Column 'C':");
        Console.WriteLine(dataFrame);
    }
}
Imports System
Imports Deedle
Friend Class Program
	Shared Sub Main()
		Dim rowIndex = { 1, 2, 3 }
		Dim colIndex = { "A", "B" }
		Dim data = New Double(, ) {
			{ 1.0, 3.5 },
			{ 2.0, 4.2 },
			{ 3.0, 5.1 }
		}
		Dim dataFrame = Frame.FromArray2D(data).IndexRowsWith(rowIndex).IndexColumnsWith(colIndex)
		Console.WriteLine("Original Data Frame:")
		Console.WriteLine(dataFrame)

		' Filter rows where column 'A' is greater than 1.5
		Dim filteredFrame = dataFrame.Where(Function(row) row.Value.GetAs(Of Double)("A") > 1.5)
		Console.WriteLine("Filtered Data Frame:")
		Console.WriteLine(filteredFrame)

		dataFrame.AddColumn("C", dataFrame("A") + dataFrame("B"))
		Console.WriteLine("Transformed Data Frame with New Column 'C':")
		Console.WriteLine(dataFrame)
	End Sub
End Class
VB   C#

這個範例展示了如何根據條件過濾行並新增一個含有轉換資料的欄位。Deedle 實現了標準框架擴展方法,使資料分析變得簡單明瞭。

統計函數

Deedle 提供標準的統計函數來分析數據。使用這些統計函數,你可以計算平均值、標準差和其他統計量。

using System;
using Deedle;
class Program
{
    static void Main()
    {
        var series = new Series<int, double>(
            new[] { 1, 2, 3, 4 },
            new[] { 1.0, 2.0, 3.0, 4.0 }
        );
        Console.WriteLine("Series:");
        Console.WriteLine(series);

        // Calculate mean
        var mean = series.Mean();
        Console.WriteLine($"Mean: {mean}");

        // Calculate standard deviation
        var stddev = series.StdDev();
        Console.WriteLine($"Standard Deviation: {stddev}");
    }
}
using System;
using Deedle;
class Program
{
    static void Main()
    {
        var series = new Series<int, double>(
            new[] { 1, 2, 3, 4 },
            new[] { 1.0, 2.0, 3.0, 4.0 }
        );
        Console.WriteLine("Series:");
        Console.WriteLine(series);

        // Calculate mean
        var mean = series.Mean();
        Console.WriteLine($"Mean: {mean}");

        // Calculate standard deviation
        var stddev = series.StdDev();
        Console.WriteLine($"Standard Deviation: {stddev}");
    }
}
Imports System
Imports Deedle
Friend Class Program
	Shared Sub Main()
		Dim series As New Series(Of Integer, Double)( { 1, 2, 3, 4 }, { 1.0, 2.0, 3.0, 4.0 })
		Console.WriteLine("Series:")
		Console.WriteLine(series)

		' Calculate mean
		Dim mean = series.Mean()
		Console.WriteLine($"Mean: {mean}")

		' Calculate standard deviation
		Dim stddev = series.StdDev()
		Console.WriteLine($"Standard Deviation: {stddev}")
	End Sub
End Class
VB   C#

此Deedle程式碼範例實現了標準統計功能 Mean()StdDev()分別計算一組數據的平均值和標準差。

從CSV創建數據框

Deedle 允許您輕鬆從 CSV 文件創建數據框。這對於加載和分析結構化數據非常有幫助。

using System;
using Deedle;
class Program
{
    static void Main()
    {
        // Load data frame from CSV file
        var dataFrame = Frame.ReadCsv("data.csv");
        Console.WriteLine("Data Frame from CSV:");
        Console.WriteLine(dataFrame);

        var summary = dataFrame.AggregateRowsBy<string, double>(
            new[] { "ColumnName" }, // rowKeys
            null, // columnKeys, you can pass null if not required
            v => v.Sum() // aggFunc
        );
        Console.WriteLine("Summary of Data Frame:");
        Console.WriteLine(summary);
    }
}
using System;
using Deedle;
class Program
{
    static void Main()
    {
        // Load data frame from CSV file
        var dataFrame = Frame.ReadCsv("data.csv");
        Console.WriteLine("Data Frame from CSV:");
        Console.WriteLine(dataFrame);

        var summary = dataFrame.AggregateRowsBy<string, double>(
            new[] { "ColumnName" }, // rowKeys
            null, // columnKeys, you can pass null if not required
            v => v.Sum() // aggFunc
        );
        Console.WriteLine("Summary of Data Frame:");
        Console.WriteLine(summary);
    }
}
Imports System
Imports Deedle
Friend Class Program
	Shared Sub Main()
		' Load data frame from CSV file
		Dim dataFrame = Frame.ReadCsv("data.csv")
		Console.WriteLine("Data Frame from CSV:")
		Console.WriteLine(dataFrame)

		Dim summary = dataFrame.AggregateRowsBy(Of String, Double)( { "ColumnName" }, Nothing, Function(v) v.Sum())
		Console.WriteLine("Summary of Data Frame:")
		Console.WriteLine(summary)
	End Sub
End Class
VB   C#

此範例將CSV檔案讀入資料框中,並對數據執行摘要操作。

將 Deedle 與 IronPDF 結合整合

IronPDF 介紹

Deedle C#(開發人員如何使用):圖1 - IronPDF for .NET:C# PDF 函式庫

IronPDF 是一個強大的庫,允許您在 .NET 應用程式中建立、操作和提取 PDF 檔案的內容。它非常靈活,可以處理各種與 PDF 相關的任務,例如生成 從 HTML 生成 PDF,提取文本,合併PDF檔案,以及更多功能。 將IronPDF與Deedle集成在一起,對於需要從數據框生成動態報告的數據分析和報告場景特別有用。

安裝 IronPDF

在您的 .NET 專案中,使用 NuGet 套件管理器主控台安裝 IronPDF,請添加以下命令:

Install-Package IronPdf

或者您也可以使用 NuGet 套件管理器為方案安裝 IronPDF。查找 IronPDF 套件 在搜尋結果中選擇它,然後點擊「安裝」按鈕。Visual Studio 將自動處理下載和安裝。

安裝完成後,IronPDF 可以用於您的項目。

將 IronPDF 與 Deedle 合併的使用案例

想像一下,你有一個包含一些統計數據的資料框,你想要將這些數據呈現在 PDF 報告中。Deedle 可以處理數據操作和分析部分,而 IronPDF 可以用來格式化和生成最終報告。例如,你可以生成一個包含表格、圖表和描述性統計的 PDF,使數據易於共享和展示。

用例代碼示例

這裡有一個完整的代碼示例,展示了如何將Deedle與IronPDF整合。我們將從Deedle數據框創建一個簡單的報告並使用IronPDF生成PDF。

using System;
using System.Linq;
using Deedle;
using IronPdf;

namespace DeedleIronPDFIntegration
{
    class Program
    {
        static void Main(string[] args)
        {
            IronPdf.License.LicenseKey = "License-Key";
            // Create a sample data frame
            var data = new[]
            {
                new { Name = "Robert", Age = 30, City = "New York" },
                new { Name = "Johnny", Age = 25, City = "San Francisco" },
                new { Name = "Charlie", Age = 35, City = "Los Angeles" }
            };
            var frame = Frame.FromRecords(data);

            // Convert the data frame to HTML table
            var htmlTable = "<table border='1' cellpadding='5' cellspacing='0'><thead><tr><th>Name</th><th>Age</th><th>City</th></tr></thead><tbody>" +
                            string.Join("", frame.Rows.Select(row =>
                                $"<tr><td>{row.Value.GetAs<string>("Name")}</td><td>{row.Value.GetAs<int>("Age")}</td><td>{row.Value.GetAs<string>("City")}</td></tr>")
                            ) +
                            "</tbody></table>";

            // Wrap the HTML table in basic HTML structure with CSS styling
            var htmlContent = $@"
            <html>
            <head>
                <style>
                    table {{
                        width: 100%;
                        border-collapse: collapse;
                    }}
                    th, td {{
                        border: 1px solid black;
                        padding: 8px;
                        text-align: left;
                    }}
                    th {{
                        background-color: #f2f2f2;
                    }}
                </style>
            </head>
            <body>
                {htmlTable}
            </body>
            </html>";

            // Create a PDF from the HTML
            var renderer = new ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

            // Save the PDF to file
            pdfDocument.SaveAs("f:\\DeedleReport.pdf");
            Console.WriteLine("PDF report created successfully!");
        }
    }
}
using System;
using System.Linq;
using Deedle;
using IronPdf;

namespace DeedleIronPDFIntegration
{
    class Program
    {
        static void Main(string[] args)
        {
            IronPdf.License.LicenseKey = "License-Key";
            // Create a sample data frame
            var data = new[]
            {
                new { Name = "Robert", Age = 30, City = "New York" },
                new { Name = "Johnny", Age = 25, City = "San Francisco" },
                new { Name = "Charlie", Age = 35, City = "Los Angeles" }
            };
            var frame = Frame.FromRecords(data);

            // Convert the data frame to HTML table
            var htmlTable = "<table border='1' cellpadding='5' cellspacing='0'><thead><tr><th>Name</th><th>Age</th><th>City</th></tr></thead><tbody>" +
                            string.Join("", frame.Rows.Select(row =>
                                $"<tr><td>{row.Value.GetAs<string>("Name")}</td><td>{row.Value.GetAs<int>("Age")}</td><td>{row.Value.GetAs<string>("City")}</td></tr>")
                            ) +
                            "</tbody></table>";

            // Wrap the HTML table in basic HTML structure with CSS styling
            var htmlContent = $@"
            <html>
            <head>
                <style>
                    table {{
                        width: 100%;
                        border-collapse: collapse;
                    }}
                    th, td {{
                        border: 1px solid black;
                        padding: 8px;
                        text-align: left;
                    }}
                    th {{
                        background-color: #f2f2f2;
                    }}
                </style>
            </head>
            <body>
                {htmlTable}
            </body>
            </html>";

            // Create a PDF from the HTML
            var renderer = new ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

            // Save the PDF to file
            pdfDocument.SaveAs("f:\\DeedleReport.pdf");
            Console.WriteLine("PDF report created successfully!");
        }
    }
}
Imports System
Imports System.Linq
Imports Deedle
Imports IronPdf

Namespace DeedleIronPDFIntegration
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			IronPdf.License.LicenseKey = "License-Key"
			' Create a sample data frame
			Dim data = {
				New With {
					Key .Name = "Robert",
					Key .Age = 30,
					Key .City = "New York"
				},
				New With {
					Key .Name = "Johnny",
					Key .Age = 25,
					Key .City = "San Francisco"
				},
				New With {
					Key .Name = "Charlie",
					Key .Age = 35,
					Key .City = "Los Angeles"
				}
			}
			Dim frame = Frame.FromRecords(data)

			' Convert the data frame to HTML table
			Dim htmlTable = "<table border='1' cellpadding='5' cellspacing='0'><thead><tr><th>Name</th><th>Age</th><th>City</th></tr></thead><tbody>" & String.Join("", frame.Rows.Select(Function(row) $"<tr><td>{row.Value.GetAs(Of String)("Name")}</td><td>{row.Value.GetAs(Of Integer)("Age")}</td><td>{row.Value.GetAs(Of String)("City")}</td></tr>")) & "</tbody></table>"

			' Wrap the HTML table in basic HTML structure with CSS styling
			Dim htmlContent = $"
            <html>
            <head>
                <style>
                    table {{
                        width: 100%;
                        border-collapse: collapse;
                    }}
                    th, td {{
                        border: 1px solid black;
                        padding: 8px;
                        text-align: left;
                    }}
                    th {{
                        background-color: #f2f2f2;
                    }}
                </style>
            </head>
            <body>
                {htmlTable}
            </body>
            </html>"

			' Create a PDF from the HTML
			Dim renderer = New ChromePdfRenderer()
			Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

			' Save the PDF to file
			pdfDocument.SaveAs("f:\DeedleReport.pdf")
			Console.WriteLine("PDF report created successfully!")
		End Sub
	End Class
End Namespace
VB   C#

輸出

Deedle C#(開發人員操作方法):圖2 - 使用 IronPDF 和 Deedle 生成的輸出PDF

就是這樣! 您剛剛創建了一個可以從複雜數據中處理的全功能應用程式 Deedle 並將其轉換為格式化的 PDF 報告使用 IronPDF這是一種強大的方式,可以以專業格式傳達您的數據分析結果。

結論

在這篇文章中,我們探討了如何整合 DeedleIronPDF 使用 Deedle,可以從資料框創建動態 PDF 報告。Deedle 用戶可以高效地操作和分析數據,而 IronPDF 會處理最終 PDF 文件的創建和格式化。這種組合允許您輕鬆生成專業報告,自動化從數據分析到演示的過程。

IronPDF 提供詳細的 文檔 以及各種 程式碼範例 指導您如何開始並有效利用其廣泛的功能。

IronPDF 授權 從$749起。試試看它如何提升您的報告能力。

< 上一頁
Dottrace .NET Core(對開發人員的作用)
下一個 >
C# 解構函式 (開發者如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >