Deedle C# (Como funciona para desenvolvedores)
Deedle C
Deedle é uma biblioteca poderosa para manipulação e análise de dados. Oferece quadros de dados e séries completas, permitindo que você manipule quadros de dados estruturados de forma eficiente. Deedle fornece ferramentas para dados faltantes, alinhamento de dados e aplicação de funções auxiliares com membros estáticos ofNullables e ofObservations. É amplamente utilizado em ciência de dados devido à sua flexibilidade e desempenho.
IronPDF é uma biblioteca para criar e manipular documentos PDF em .NET. Ele ajuda você a gerar PDFs a partir de HTML, converter imagens em PDFs e extrair conteúdo de arquivos PDF. IronPDF simplifica as tarefas com PDFs em seus projetos .NET .
Neste artigo, você aprenderá como começar a usar o Deedle para C#, configurá-lo em seus projetos .NET usando o Visual Studio e implementar recursos importantes com documentação gerada automaticamente. Você verá exemplos de código e explicações para ajudá-lo a entender como usar o Deedle de forma eficaz, incluindo como aplicar uma função específica.
Primeiros Passos com o Deedle C
Configurando o Deedle em projetos .NET
Para começar, crie um novo projeto de Aplicativo de Console C# no Visual Studio .
Para usar o Deedle em seu projeto .NET , você precisa instalar o pacote NuGet do Deedle. Execute o seguinte comando no console do NuGet :
Install-Package Deedle
Após a instalação, você precisa importar o namespace Deedle para o seu projeto:
using Deedle;
using Deedle;
Imports Deedle
Um exemplo de código básico
Vamos começar com um exemplo básico para criar e manipular um data frame. Isso ajudará você a entender os conceitos básicos do 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
Neste exemplo, você cria uma série com chaves de linha do tipo inteiro e valores do tipo double. Em seguida, você cria um data frame usando uma matriz 2D de valores double. Você indexa as linhas com números inteiros e as colunas com strings.
Implementando Recursos do Deedle C
Tratamento de valores ausentes
Lidar com valores ausentes é crucial na manipulação de dados. Deedle oferece suporte robusto para dados faltantes. Você pode criar uma série com valores ausentes e realizar operações para lidar com eles.
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
Este exemplo cria uma série com valores ausentes e os preenche com um valor especificado. Você também pode usar métodos de membro estáticos como ofOptionalObservations e ofValues para cenários mais complexos.
Manipulação de Dados
Deedle permite que você execute diversas tarefas de manipulação de dados. Você pode filtrar, transformar e agregar dados em data frames.
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
Este exemplo demonstra como filtrar linhas com base em uma condição e adicionar uma nova coluna com os dados transformados. Deedle implementa métodos padrão de extensão de frames para simplificar a análise de dados.
Funções Estatísticas
Deedle fornece funções estatísticas padrão para analisar dados. Utilizando as funções estatísticas, você pode calcular a média, o desvio padrão e outras medidas estatísticas.
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
Este exemplo de código Deedle implementa as funções estatísticas padrão Mean() e StdDev() para calcular a média e o desvio padrão de uma série, respectivamente.
Criando Data Frames a partir de CSV
O Deedle permite criar facilmente quadros de dados a partir de arquivos CSV. Isso é útil para carregar e analisar dados estruturados.
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
Este exemplo lê um arquivo CSV para um data frame e realiza uma operação de resumo nos dados.
Integrando Deedle com IronPDF
Introdução ao IronPDF

IronPDF é uma biblioteca poderosa que permite criar, manipular e extrair conteúdo de arquivos PDF em aplicações .NET . É extremamente versátil e pode lidar com diversas tarefas relacionadas a PDFs, como gerar PDFs a partir de HTML , extrair texto, mesclar PDFs e muito mais. A integração do IronPDF com o Deedle pode ser particularmente útil para cenários de análise de dados e geração de relatórios onde é necessário gerar relatórios dinâmicos a partir de data frames.
Instalação do IronPDF
Para instalar o IronPDF em seu projeto .NET usando o Console do Gerenciador de Pacotes NuGet , adicione o seguinte comando:
Install-Package IronPdf
Ou você também pode instalar o IronPDF usando o Gerenciador de Pacotes NuGet para Soluções. Procure o pacote IronPDF no NuGet nos resultados da pesquisa, selecione-o e clique no botão "Instalar". O Visual Studio cuidará do download e da instalação automaticamente.
Após a conclusão da instalação, o IronPDF poderá ser utilizado em seu projeto.
Caso de uso da integração do IronPDF com o Deedle
Imagine que você tem um conjunto de dados com algumas informações estatísticas que deseja apresentar em um relatório em PDF. O Deedle pode lidar com a manipulação e análise dos dados, enquanto o IronPDF pode ser usado para formatar e gerar o relatório final. Por exemplo, você pode gerar um PDF que inclua tabelas, gráficos e estatísticas descritivas, facilitando o compartilhamento e a apresentação dos dados.
Exemplo de código de caso de uso
Aqui está um exemplo de código completo demonstrando como integrar o Deedle com o IronPDF. Criaremos um relatório simples a partir de um dataframe Deedle e geraremos um PDF usando o IronPDF.
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
Saída

E é isso! Você acabou de criar um aplicativo totalmente funcional que extrai dados complexos do Deedle e os transforma em um relatório PDF formatado usando a biblioteca .NET PDF do IronPDF . É uma forma eficaz de comunicar os resultados da sua análise de dados em um formato profissional.
Conclusão
Neste artigo, exploramos como integrar o Deedle com o IronPDF para criar relatórios PDF dinâmicos a partir de data frames. Com o Deedle, você pode manipular e analisar dados de forma eficiente, enquanto o IronPDF cuida da criação e formatação do documento PDF final. Essa combinação permite gerar relatórios profissionais com facilidade, automatizando o processo desde a análise de dados até a apresentação.
O IronPDF oferece documentação detalhada sobre recursos e uso, juntamente com vários exemplos de código IronPDF para orientá-lo sobre como começar e usar efetivamente seus extensos recursos.
Explore as opções de licenciamento do IronPDF a partir de $799. Experimente e veja como isso pode aprimorar suas capacidades de geração de relatórios.
Perguntas frequentes
Para que serve o Deedle C#?
Deedle C# é usado para manipulação e análise de dados, fornecendo ferramentas para lidar de forma eficiente com data frames e séries estruturadas. É particularmente útil em aplicações de ciência de dados devido à sua capacidade de gerenciar dados faltantes, alinhar dados e aplicar funções.
Como posso integrar o Deedle com a geração de PDFs em .NET?
Você pode integrar o Deedle com o IronPDF para gerar relatórios PDF dinâmicos a partir de dataframes. O Deedle lida com a manipulação dos dados, enquanto o IronPDF é usado para formatar e gerar o relatório PDF final, completo com tabelas, gráficos e estatísticas.
Como instalar o Deedle em um projeto .NET?
Para instalar o Deedle em um projeto .NET, você pode usar o Visual Studio para criar um novo aplicativo de console C#, instalar o pacote NuGet do Deedle usando o comando Install-Package Deedle e incluí-lo em seu projeto com using Deedle; .
Qual é o processo para criar data frames a partir de arquivos CSV usando o Deedle?
Para criar data frames a partir de arquivos CSV usando o Deedle, você pode usar o método Frame.ReadCsv() . Isso permite carregar dados estruturados de arquivos CSV em data frames para análise e manipulação.
O Deedle consegue lidar com valores ausentes em data frames?
Sim, o Deedle oferece suporte robusto para lidar com valores ausentes em data frames. Você pode usar funções como FillMissing() para gerenciar e preencher dados ausentes adequadamente em uma série ou em um data frame.
Como posso realizar análises estatísticas usando o Deedle?
O Deedle oferece funções estatísticas integradas que permitem realizar análises de dados, incluindo cálculos de média, desvio padrão e outras métricas estatísticas diretamente em data frames e séries.
Como gerar relatórios em PDF a partir de data frames no .NET?
Para gerar relatórios em PDF a partir de data frames no .NET, você pode usar o Deedle para manipulação de dados e o IronPDF para geração do PDF. Após manipular os dados com o Deedle, use o IronPDF para formatar e gerar um relatório em PDF com aparência profissional.




