c# - 在 .Net Windows 应用程序窗体中计算 DataGridView 中每个元素的频率
问题描述
我有一些从 csv 文件读取到 DataGridViews 的数据集,我需要绘制一些图表,在其中计算每列上每个不同变量的频率。
我找到了一个计算数组元素频率然后打印它们的代码,我尝试在我的数据网格上使用相同的逻辑。
我从一个只有 2 个值(2.0
或1.0
)的列(“SEX”列)开始,但是当我尝试查看计数结果时,我总是得到1
(这意味着它没有计算任何东西)。它应该显示在列中找到的最后一个不同值的计数(在我的例子2.0
中,它出现了 140 次)。
编辑:我尝试将计数结果附加到文本框,我看到我最终1
得到每个循环,而我应该只得到 2 个值(这是计数2.0
,然后是计数1.0
)
我还需要绘制输出,所以我猜我可以使用字典来存储变量名+频率。
public void countFreq() //function to count the frequency of each var in a column -not working yet-
{
var n = dataGridView1.RowCount;
var visited = new bool[n];
// Traverse through array elements and
// count frequencies
for (var i = 0; i < n; i++)
{
// Skip this element if already processed
if (visited[i] || dataGridView1.Rows[i].Cells["SEX"].Value
== null)
continue;
// Count frequency
var count = 1;
for (var j = i + 1; j < n; j++)
if (dataGridView1.Rows[i].Cells["SEX"].Value == dataGridView1.Rows[j].Cells["SEX"].Value)
{
visited[j] = true;
count++;
}
textFile.Text += count.ToString(); //for testing purposes I used a textfield to print the last count value
}
}
我知道对于值是显式的列,我可以在我的数据网格行上循环并使用计数方法(我做过)但是对于我的大多数数据,我没有明确知道每一行中的值,所以我需要找到一种方法来做到这一点。
解决方案
我不确定这是否是您正在寻找的。此外,下面的代码循环遍历网格中的行,但是,如果网格有数据源,我建议循环通过该集合而不是网格行。
下面是一个采用列索引并返回Dictionary<string, int>
. 一个简单的循环遍历给定列中的每个单元格,如果单元格Value
不在字典中,我们将添加它。如果单元格值已经在字典中,将简单地增加其int
Value
. 循环结束后,返回字典。像……</p>
private Dictionary<string, int> GetCountOfValues(string columnName) {
string curKey = "";
Dictionary<string, int> valuesAndCounts = new Dictionary<string, int>();
foreach (DataGridViewRow row in dataGridView1.Rows) {
if (!row.IsNewRow) {
if (row.Cells[columnName].Value != null) {
curKey = row.Cells[columnName].Value.ToString();
if (valuesAndCounts.ContainsKey(curKey)) {
valuesAndCounts[curKey]++;
}
else {
valuesAndCounts.Add(curKey, 1);
}
}
}
}
return valuesAndCounts;
}
用法可能看起来像……</p>
Dictionary<string, int> column0Counts = GetCountOfValues("Col0");
Dictionary<string, int> column1Counts = GetCountOfValues("Date");
推荐阅读
- python - 我可以在整个数据集上使用 StandardScaler(),还是应该分别在训练集和测试集上计算?
- python - 流出函数的打印语句
- java - 在 AIX 上为 Tomcat 上的 HTTP2 使用 tcnative 模块
- r - 如何找出在 R 数据框中是否满足特定 ID 的特定条件?
- typescript - NestJS/Prisma 在没有任何附加信息的情况下给出“错误调试失败”
- linux - Bash - 执行命令并显示输出,然后 grep 以获取摘要(拉取所有 git repos)
- swift - SwiftUI,将视图分配给变量
- html - 打字机效果。单独打印文本
- flutter - 无法使用 ListView.builder() 滚动
- python - 如何在python中使用BeautifulSoup按顺序提取字符串(例如:9、4、1、6、3 ...)