跳至页脚内容
.NET 帮助

Deedle C#(开发人员如何使用)

Deedle C#

Deedle 是一个用于数据操作和数据分析的强大库。 它提供整个数据框架和系列,允许您高效地处理结构化数据框架。 Deedle 提供处理丢失数据、对齐数据的工具,并通过静态成员 ofNullablesofObservations 应用辅助函数。 它因其灵活性和性能在数据科学中被广泛使用。

IronPDF 是一个用于在 .NET 中创建和操作 PDF 文档的库。 它帮助您从 HTML 生成 PDF,将图像转换为 PDF,并从 PDF 文件中提取内容。 IronPDF 简化了您 .NET 项目中的 PDF 任务。

在本文中,您将学习如何开始使用 Deedle for C#,如何在您的 .NET 项目中使用 Visual Studio 设置它,并通过自动生成的文档实现关键功能。 您将看到代码示例和解释,以帮助您了解如何有效地使用 Deedle,包括如何应用指定函数。

Getting Started with Deedle C#

Setting Up Deedle in .NET Projects

首先,在 Visual Studio 中创建一个新的 C# 控制台应用程序项目。

要在 .NET 项目中使用 Deedle,需要安装 Deedle NuGet 包。 在 NuGet 控制台中运行以下命令:

Install-Package Deedle

安装后,您需要将 Deedle 命名空间导入到您的项目中:

using Deedle;
using Deedle;
Imports Deedle
$vbLabelText   $csharpLabel

基本代码示例

让我们从一个基本示例开始来创建和操作一个数据框架。 这将帮助您理解 Deedle 的基础知识。

using System;
using Deedle;

class Program
{
    static void Main()
    {
        // Creating a series with integer keys and double values
        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 from a 2D array
        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 with integer keys and double values
        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 from a 2D array
        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 with integer keys and double values
		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 from a 2D array
		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
$vbLabelText   $csharpLabel

在此示例中,您创建一个具有整数行键和双精度值的系列。 然后,您使用二维数组的双精度值创建数据框架。 您使用整数为行和字符串为列进行索引。

Implementing Features of Deedle C#

Handling Missing Values

处理缺失值在数据操作中至关重要。 Deedle 提供了对缺失数据的强大支持。 您可以创建一个具有缺失值的系列,并执行操作来处理它们。

using System;
using Deedle;

class Program
{
    static void Main()
    {
        // Creating a series with nullable doubles to represent missing values
        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 (e.g., 0.0)
        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()
    {
        // Creating a series with nullable doubles to represent missing values
        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 (e.g., 0.0)
        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()
		' Creating a series with nullable doubles to represent missing values
		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 (e.g., 0.0)
		Dim filledSeries = series.FillMissing(0.0)
		Console.WriteLine("Series after Filling Missing Values:")
		Console.WriteLine(filledSeries)
	End Sub
End Class
$vbLabelText   $csharpLabel

此示例创建一个具有缺失值的系列,并用指定值填充值。 您还可以使用 ofOptionalObservationsofValues 等静态成员方法来处理更复杂的情况。

Data Manipulation

Deedle 允许您执行各种数据操作任务。 您可以过滤、转换和汇总数据框架中的数据。

using System;
using Deedle;

class Program
{
    static void Main()
    {
        // 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("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);

        // Add a new column 'C' which is the sum of columns 'A' and 'B'
        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()
    {
        // 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("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);

        // Add a new column 'C' which is the sum of columns 'A' and 'B'
        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()
		' 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("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)

		' Add a new column 'C' which is the sum of columns 'A' and 'B'
		dataFrame.AddColumn("C", dataFrame("A") + dataFrame("B"))
		Console.WriteLine("Transformed Data Frame with New Column 'C':")
		Console.WriteLine(dataFrame)
	End Sub
End Class
$vbLabelText   $csharpLabel

此示例演示了如何根据条件过滤行,并添加一个包含转换数据的新列。 Deedle 实现了标准的框架扩展方法,使得数据分析变得简单。

Statistical Functions

Deedle 提供了标准的统计函数来分析数据。 使用统计函数,您可以计算平均值、标准差和其他统计度量。

using System;
using Deedle;

class Program
{
    static void Main()
    {
        // Creating a series with integer keys and double values
        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 the mean of the series
        var mean = series.Mean();
        Console.WriteLine($"Mean: {mean}");

        // Calculate the standard deviation of the series
        var stddev = series.StdDev();
        Console.WriteLine($"Standard Deviation: {stddev}");
    }
}
using System;
using Deedle;

class Program
{
    static void Main()
    {
        // Creating a series with integer keys and double values
        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 the mean of the series
        var mean = series.Mean();
        Console.WriteLine($"Mean: {mean}");

        // Calculate the standard deviation of the series
        var stddev = series.StdDev();
        Console.WriteLine($"Standard Deviation: {stddev}");
    }
}
Imports System
Imports Deedle

Friend Class Program
	Shared Sub Main()
		' Creating a series with integer keys and double values
		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 the mean of the series
		Dim mean = series.Mean()
		Console.WriteLine($"Mean: {mean}")

		' Calculate the standard deviation of the series
		Dim stddev = series.StdDev()
		Console.WriteLine($"Standard Deviation: {stddev}")
	End Sub
End Class
$vbLabelText   $csharpLabel

这个 Deedle 代码示例实现了标准的统计函数 Mean()StdDev(),分别用于计算系列的平均值和标准差。

Creating Data Frames from CSV

Deedle 让您可以轻松地从 CSV 文件中创建数据框架。 这对于加载和分析结构化数据很有帮助。

using System;
using Deedle;

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

        // Aggregate rows by a specified column and compute sum
        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 a data frame from a CSV file
        var dataFrame = Frame.ReadCsv("data.csv");
        Console.WriteLine("Data Frame from CSV:");
        Console.WriteLine(dataFrame);

        // Aggregate rows by a specified column and compute sum
        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 a data frame from a CSV file
		Dim dataFrame = Frame.ReadCsv("data.csv")
		Console.WriteLine("Data Frame from CSV:")
		Console.WriteLine(dataFrame)

		' Aggregate rows by a specified column and compute sum
		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
$vbLabelText   $csharpLabel

此示例将 CSV 文件读取到数据框架中,并对数据执行汇总操作。

Integrating Deedle with IronPDF

IronPDF介绍

Deedle C# (How It Works For Developers): Figure 1 - IronPDF for .NET: The C# PDF Library

IronPDF 是一个强大的库,可以让您在 .NET 应用程序中创建、操作和提取 PDF 文件内容。 它具有很高的灵活性,可以处理各种与 PDF 相关的任务,如从 HTML 生成 PDF,提取文本,合并 PDF 等等。 将 IronPDF 与 Deedle 集成在一起对于数据分析和报告场景尤其有用,在这些场景中您需要从数据框架生成动态报告。

Installation of IronPDF

要在您的 .NET 项目中使用 NuGet 包管理器控制台安装 IronPDF,添加以下命令:

Install-Package IronPdf

或者,您也可以使用 NuGet 包管理器安装 IronPDF。 在搜索结果中查找 IronPDF 包,选择它,然后点击“安装”按钮。 ### 4.2 使用NuGet包管理器控制台安装

安装完成后,可以在您的项目中使用 IronPDF。

Use Case of Merging IronPDF with 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)
        {
            // Set IronPDF license key
            IronPdf.License.LicenseKey = "License-Key";

            // Create a sample data frame from in-memory records
            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 an HTML table format
            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 content
            var renderer = new ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

            // Save the generated PDF to a 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)
        {
            // Set IronPDF license key
            IronPdf.License.LicenseKey = "License-Key";

            // Create a sample data frame from in-memory records
            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 an HTML table format
            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 content
            var renderer = new ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

            // Save the generated PDF to a 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)
			' Set IronPDF license key
			IronPdf.License.LicenseKey = "License-Key"

			' Create a sample data frame from in-memory records
			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 an HTML table format
			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 content
			Dim renderer = New ChromePdfRenderer()
			Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

			' Save the generated PDF to a file
			pdfDocument.SaveAs("f:\DeedleReport.pdf")
			Console.WriteLine("PDF report created successfully!")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

输出

Deedle C# (How It Works For Developers): Figure 2 - Output PDF generated using IronPDF and Deedle

就这样! You've just created a fully functional application that takes complex data from Deedle and turns it into a formatted PDF report using IronPDF's .NET PDF Library. 这是一种强大的方式,可以以专业格式传达您的数据分析结果。

结论

In this article, we've explored how to integrate Deedle with IronPDF to create dynamic PDF reports from data frames. 使用 Deedle,您可以有效地操作和分析数据,而 IronPDF 负责创建和格式化最终的 PDF 文档。 这种组合使您可以轻松生成专业报告,从数据分析到演示自动化。

IronPDF offers detailed documentation on features and usage along with various IronPDF code examples to guide you on how to get started and effectively use its extensive features.

探索 IronPDF 许可选项,起价为$799。 试一试,看看它如何增强您的报告能力。

常见问题解答

Deedle C# 用于什么?

Deedle C# 用于数据处理和分析,提供工具以高效处理结构化数据框和序列。它在数据科学应用中特别有用,因其能够管理缺失数据,对齐数据和应用函数。

如何在 .NET 中将 Deedle 与 PDF 生成集成?

您可以将 Deedle 与 IronPDF 集成,从数据框生成动态的 PDF 报告。Deedle 负责数据操作,而 IronPDF 用于格式化并生成最终的 PDF 报告,包括表格、图表和统计数据。

如何在 .NET 项目中安装 Deedle?

要在 .NET 项目中安装 Deedle,您可以使用 Visual Studio 创建一个新的 C# 控制台应用程序,然后使用命令 Install-Package Deedle 安装 Deedle NuGet 包,并通过 using Deedle; 将其包含在项目中。

使用 Deedle 从 CSV 文件创建数据框的过程是怎样的?

使用 Deedle 从 CSV 文件创建数据框,您可以使用 Frame.ReadCsv() 方法。这使您可以将结构化数据从 CSV 文件加载到数据框中进行分析和操作。

Deedle 能处理数据框中的缺失值吗?

是的,Deedle 提供了强大的功能来处理数据框中的缺失值。您可以使用类似 FillMissing() 的函数来适当地管理和填充系列或数据框中的缺失数据。

如何使用 Deedle 执行统计分析?

Deedle 提供内置的统计函数,允许您直接在数据框和序列上执行数据分析,包括平均值、标准差和其他统计指标的计算。

如何在 .NET 中从数据框生成 PDF 报告?

要在 .NET 中从数据框生成 PDF 报告,您可以使用 Deedle 进行数据处理,并使用 IronPDF 进行 PDF 生成。在使用 Deedle 操作数据后,使用 IronPDF 将数据格式化并输出成专业风格的 PDF 报告。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。