如果我想问一问如何使用PHP或Javascipt搜索CSV文件的列的最大值,
这是我的csv文件表:
image,category,prob
"data/test1.jpg",zero1,0.947648
"data/test1.jpg",zero1,0.957323
"data/test1.jpg",zero1,0.955677
"data/test1.jpg",zero1,0.951940
"data/test1.jpg",zero1,0.950025
我想找到最高概率列,并打印其类别值。
我寻找的输出是这样的:
zero1,0.957323
感谢您的帮助
答案 0 :(得分:0)
在PHP中,您可以使用fgetcsv
来读取数据:
$handle = fopen("test.csv", "r");
// read the headers
$data = fgetcsv($handle);
// read the data
$max_prob = 0;
$category_max = '';
while (($data = fgetcsv($handle)) !== false) {
if ($data[2] > $max_prob) {
$max_prob = $data[2];
$category_max = $data[1];
}
}
echo "max prob value is $max_prob for category $category_max\n";
答案 1 :(得分:0)
好,所以通常在SO上,您想说出您尝试过的内容,遇到了什么错误等,否则您的问题可能会被删除。但是,这里有:
var originalString = `"data/test1.jpg",zero1,0.947648
"data/test1.jpg",zero1,0.957323
"data/test1.jpg",zero1,0.955677
"data/test1.jpg",zero1,0.951940
"data/test1.jpg",zero1,0.950025`;
var oneDArray = originalString.split('\n\r'); // split on the return characters, you may have to play with this to get it to work.
var twoDAttay = oneDArray.map( line => line.split(",") ); // make an array of 3 elements for each line, split by the commas.
因此,您现在拥有了:
twoDArray = [
["data/test1.jpg",zero1,0.947648],
["data/test1.jpg",zero1,0.957323],
["data/test1.jpg",zero1,0.955677],
["data/test1.jpg",zero1,0.951940],
["data/test1.jpg",zero1,0.950025]
];
所有数字都在每个内部数组的2
点中。现在我们准备找到最大数量,我们只需要将它们放在自己的数组中即可:
var numArray = twoDArray.map( line => Number( line[2] )); // get only the numbers
var maxNum = Math.max( ...numArray ); // find the maximum number
var index = numArray.indexOf( maxNum ); // find the index of the max number, this will correspond to the oneDArray.
var maxLine = oneDarray[ index ]; // This is your answer
但是,在获得二维数组之后,有许多方法可以使用它:Finding the max value of an attribute in an array of objects。使用最适合您的版本。最难的部分是将数据清理为js可以理解的格式-那些带引号和未引号的字符串将成为问题。