find Math.min row

给你一囗甜甜゛ 提交于 2020-03-05 04:58:06

问题


I have already found the lowest value in a column in a csv file, but I can't find which row store this value. Can someone help me please? Is there anyway I can find the answer by myself though I have googled for many days and websites. Thanks in advance.

function getDataPointsFromCSV(csv) {
            var dataPoints = csvLines =   [];   
            var mini, a
            var minIndex = 0
            csvLines = csv.split(/[\r?\n|\r|\n]+/);
            for (var i = 1; i <= csvLines.length; i++)
                if (csvLines[i] > 0) {
                    points = csvLines[i].split(",");
//points instead of csvLines
                    mini = points[4]
                }
            var a = mini                
            for (var i = 1; i <= csvLines.length; i++)
                if (csvLines[i] < mini) {
                    points = csvLines[i].split(",");                    

                    minIndex = i
                    mini = csvLines[i]                                      
// Find lowest value in a column5(=points[4])( but how to find the row that store the lowest value, can someone help me please?)                
                    lowestv = Math.min(price, lowestv)
             }
// example; mini.length          
            for (var i = mini.length; i <= mini.length+10; i++)
                if (csvLines[i].length > 0) {
                    points = csvLines[i].split(",");
                    price = points[4]
            }
                dataPoints.push({x: new Date(),y: parseFloat(minIndex)});   
        return dataPoints;
        }

回答1:


I provide a snippet, that uses the sample data in your comment:

const csv = "date,open,high,low,close\n31/10/2019,9202.457589,9383.160892,9028.71744,9199.584833\n30/10/2019,9422.463325,9426.874217,9085.370357,9205.726559\n29/10/2019,9248.440562,9516.181048,9232.648086,9427.687584\n28/10/2019,9565.101883,9805.118089,9256.148389,9256.148389"
const lines = csv.split(/[\r?\n|\r|\n]+/)
const header = lines.shift().split(',') // chop off header, and store it in a variable
const cells = lines.map(e => e.split(',').map(n => !isNaN(n) ? Number(n) : n))

// transpose the array, so it's easier to get min/max
// transposing (rows become columns and columns become rows)
// [[a, b],[c, d]] ==> [[a, c], [b, d]]
const transpose = cells[0].map((e, i) => {
  return cells.map(el => {
    return el[i]
  })
})
const dates = transpose.shift() // chop off dates, and store them in a variable

const rowRange = transpose.map((e, i) => {
  const min = Math.min(...e)
  const max = Math.max(...e)
  return {
    col: i + 1, // +1, because dates are chopped off
    colName: header[i + 1],
    max,
    maxRow: e.indexOf(max) + 1, // +1, because header is chopped off
    maxRowDate: dates[e.indexOf(max)],
    min,
    minRow: e.indexOf(min) + 1, // +1, because header is chopped off
    minRowDate: dates[e.indexOf(min)]
  }
})

console.log("result:", rowRange)

I added min AND max (and a couple of other properties) so you could use it in more cases.

IMPORTANT NOTE

This solution mutates the array parsed from the CSV.




回答2:


I would break this into two steps. First, we parse the CSV to get an array of objects. Then we iterate over them to find stats like minVal and minRow (and any others we might want.) While this is slightly less efficient than doing it in a single pass, it leads to simpler, more maintainable code.

So here we have csv2arr, which converts your CSV string into objects that look like this:

{
    date: "31/10/2019",
    open: 9202.457589,
    high: 9383.160892,
    low: 9028.71744,
    close: 9199.584833
}

and stats, which takes an array of objects like that to find statistics such as maxVal and minRow for each column. We could enhance this to find other stats such as mean and median if desired. Its output looks like this:

{
    date: { /* ... */ },
    open: { /* ... */ },
    high: { /* ... */ },
    low: { /* ... */ },
    close: {
        minVal: 9199.584833,
        maxVal: 9427.687584,
        minRow: {date: "31/10/2019", open: 9202.457589, high: 9383.160892, low: 9028.71744, close: 9199.584833},
        maxRow: {date: "29/10/2019", open: 9248.440562, high: 9516.181048, low: 9232.648086, close: 9427.687584}
    }
}

This is one way to do so:

// Naive, but useful for some data
const csv2arr = (csv) => {
  const [headers, ...rows] = csv .trim () .split ('\n') .map (r => r .split (','))
  return rows .reduce ((a, r) => [
    ... a, 
    Object .assign (... (r .map ((c, i) => ({[headers [i]]: isNaN(c) ? c : Number(c)}))))
  ], [])
}

const stats = (rows) => rows .reduce (
  (stats, row) => Object .assign (
    ... Object .entries (row) .map (([key, val]) => ({[key]: ({
      minVal: key in stats && stats [key] .minVal < val ? stats [key] .minVal : val,
      maxVal: key in stats && stats [key] .maxVal > val ? stats [key] .maxVal : val,
      minRow: key in stats && stats [key] .minRow [key] < val ? stats [key] .minRow : row,
      maxRow: key in stats && stats [key] .maxRow [key] > val ? stats [key] .maxRow : row,
    })}))
  ),
  {}
)

const csv = `
date,open,high,low,close
31/10/2019,9202.457589,9383.160892,9028.71744,9199.584833
30/10/2019,9422.463325,9426.874217,9085.370357,9205.726559
29/10/2019,9248.440562,9516.181048,9232.648086,9427.687584
28/10/2019,9565.101883,9805.118089,9256.148389,9256.148389
`

const rows = csv2arr (csv)
const statistics = stats (rows)

console .log (rows)
console .log (statistics)

Note that the min/max values for dates here don't make much sense. If they were ISO-formatted (e.g. "2019-10-31"), then these values would also get meaningful maximums and minimums.

csv2arr is useful for a reasonably wide range of cases. But don't mistake it for a full CSV parser. If your data includes cells with commas, for instance, it will fail. It's also naive about the output. Essentially, if it looks like a number, it becomes a number, even if other things in the column disagree. There are other problems, too. But it's still useful for many comma-delimited formats.



来源:https://stackoverflow.com/questions/59935949/find-math-min-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!