AYUDA .NET

Deedle C# (Cómo funciona para desarrolladores)

Actualizado julio 1, 2024
Compartir:

Escritura C

"Aguja es una potente biblioteca para la manipulación y el análisis de datos. Ofrece marcos de datos enteros y series, lo que le permite manejar marcos de datos estructurados de forma eficaz. Deedle proporciona herramientas para los datos que faltan, alineación de datos, y la aplicación de funciones de ayuda con los miembros estáticos ofNullables y ofObservations. Se utiliza ampliamente en la ciencia de datos por su flexibilidad y rendimiento.

IronPDF es una biblioteca para crear y manipular documentos PDF en .NET. Le ayuda a generar PDF a partir de HTML, convertir imágenes en PDF y extraer contenido de archivos PDF. IronPDF simplifica las tareas de PDF en sus proyectos .NET.

En este artículo, aprenderá a empezar a utilizar Deedle para C#, a configurarlo en sus proyectos .NET mediante Visual Studio y a implementar funciones clave con documentación generada automáticamente. Verá ejemplos de código y explicaciones que le ayudarán a entender cómo utilizar Deedle de forma eficaz, incluyendo cómo aplicar una función especificada.

Primeros pasos con Deedle C

Configuración de Deedle en proyectos .NET

Para empezar, cree un nuevo proyecto de aplicación de consola C# en Visual Studio.

Para utilizar Deedle en su proyecto .NET, debe instalar el paquete NuGet de Deedle. Ejecute el siguiente comando en la consola NuGet:

Install-Package Deedle

Una vez instalado, debes importar el espacio de nombres Deedle a tu proyecto:

using Deedle;
using Deedle;
Imports Deedle
VB   C#

Un ejemplo de código básico

Empecemos con un ejemplo básico para crear y manipular un marco de datos. Esto le ayudará a entender los conceptos básicos de 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#

En este ejemplo, se crea una serie con claves de fila enteras y valores dobles. A continuación, se crea un marco de datos utilizando una matriz 2D de valores dobles. Se indexan las filas con enteros y las columnas con cadenas.

Implementación de funciones de Deedle C

Tratamiento de valores perdidos

El tratamiento de los valores perdidos es crucial en la manipulación de datos. Deedle ofrece un sólido soporte para los datos que faltan. Puede crear una serie con valores perdidos y realizar operaciones para manejarlos.

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#

Este ejemplo crea una serie con valores perdidos y los rellena con un valor especificado. También puedes utilizar métodos estáticos como ofOptionalObservations y ofValues para escenarios más complejos.

Manipulación de datos

Deedle permite realizar diversas tareas de manipulación de datos. Puede filtrar, transformar y agregar datos en marcos de datos.

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#

Este ejemplo demuestra el filtrado de filas basado en una condición y la adición de una nueva columna con datos transformados. Deedle implementa métodos estándar de ampliación de marcos para facilitar el análisis de datos.

Funciones estadísticas

Deedle proporciona funciones estadísticas estándar para analizar los datos. Las funciones estadísticas permiten calcular la media, la desviación típica y otras medidas estadísticas.

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#

Este ejemplo de código de Deedle implementa las funciones estadísticas estándar Media() y StdDev() para calcular la media y la desviación típica de una serie respectivamente.

Creación de marcos de datos a partir de CSV

Deedle permite crear fácilmente marcos de datos a partir de archivos CSV. Esto es útil para cargar y analizar datos estructurados.

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#

Este ejemplo lee un archivo CSV en un marco de datos y realiza una operación de resumen de los datos.

Integración de Deedle con IronPDF

Presentación de IronPDF

Escritura C# (Cómo funciona para desarrolladores): Figura 1 - IronPDF for .NET: La biblioteca PDF de C#

IronPDF es una potente biblioteca que permite crear, manipular y extraer contenido de archivos PDF en aplicaciones .NET. Es muy versátil y puede realizar varias tareas relacionadas con PDF, como generar PDF a partir de HTMLextraer texto, fusionar PDF y mucho más. La integración de IronPDF con Deedle puede ser especialmente útil para el análisis de datos y la elaboración de informes en situaciones en las que es necesario generar informes dinámicos a partir de marcos de datos.

Instalación de IronPDF

Para instalar IronPDF en su proyecto .NET utilizando la Consola del Gestor de Paquetes NuGet, añada el siguiente comando:

Install-Package IronPdf

También puede instalar IronPDF utilizando NuGet Package Manager for Solutions. Busque el Paquete IronPDF en los resultados de la búsqueda, selecciónelo y haga clic en el botón "Instalar". Visual Studio se encargará de la descarga y la instalación automáticamente.

Una vez finalizada la instalación, IronPDF puede utilizarse para su proyecto.

Caso práctico de la fusión de IronPDF con Deedle

Imagine que tiene un marco de datos con algunos datos estadísticos que desea presentar en un informe PDF. Deedle puede encargarse de la parte de manipulación y análisis de datos, mientras que IronPDF puede utilizarse para dar formato y generar el informe final. Por ejemplo, puede generar un PDF que incluya tablas, gráficos y estadísticas descriptivas, para que los datos sean fáciles de compartir y presentar.

Ejemplo de código del caso de uso

Aquí tiene un ejemplo de código completo que demuestra cómo integrar Deedle con IronPDF. Crearemos un informe sencillo a partir de un marco de datos Deedle y generaremos un PDF utilizando IronPDF.

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#

Salida

Escritura C# (Cómo funciona para desarrolladores): Figura 2 - PDF de salida generado usando IronPDF y Deedle

Y eso es todo.! Acaba de crear una aplicación totalmente funcional que toma datos complejos de Deedle y lo convierte en un informe PDF formateado utilizando IronPDF. Es una forma eficaz de comunicar los resultados de sus análisis de datos en un formato profesional.

Conclusión

En este artículo, hemos explorado cómo integrar Deedle con IronPDF para crear informes PDF dinámicos a partir de marcos de datos. Con Deedle, puede manipular y analizar datos de forma eficaz, mientras que IronPDF se encarga de la creación y el formato del documento PDF final. Esta combinación le permite generar informes profesionales con facilidad, automatizando el proceso desde el análisis de los datos hasta su presentación.

IronPDF ofrece información detallada documentación junto con varios ejemplos de código para guiarte sobre cómo empezar y utilizar eficazmente sus amplias funciones.

Licencias IronPDF a partir de 749 $. Pruébelo y vea cómo puede mejorar su capacidad de elaboración de informes.

< ANTERIOR
Dottrace .NET Core (Cómo funciona para desarrolladores)
SIGUIENTE >
C# Deconstructor (Cómo funciona para desarrolladores)

¿Listo para empezar? Versión: 2024.9 acaba de salir

Descarga gratuita de NuGet Descargas totales: 10,516,730 View Licenses >