Home > Software design >  how to caculate the avg of column from a csv which does not have headers with powershell?
how to caculate the avg of column from a csv which does not have headers with powershell?

Time:08-19

The data array inside the csv which does not have headers(shoudl be: pkg, pp0, pp1, dram, time):

37.0036,27.553,0,0,0.100111
35.622,26.1947,0,0,0.200702
34.931,25.5656,0,0,0.300765
34.814,25.4795,0,0,0.400826
34.924,25.5676,0,0,0.500888
34.8971,25.5443,0,0,0.600903

if I want to get the avg value of the columns and make the output like:

The avg of Pkg: xxx
The avg of pp0: xxx
The avg of pp1: xxx
The avg of time: xxx

how can I do?

CodePudding user response:

When you're using Import-CSV, PowerShell references the first row as the header row. The error you're getting,

import-csv : The member "0" is already present.

Is because there is already a header name of 0 in the header row. To give new names to the headers, use the Import-CSV -Header command to give manual names in the csv file.

From here, you can use the Measure-Object command to determine the averages

$myData = Import-Csv .\a.csv -Header pkg,pp0,pp1,dram,time
Write-Host "The avg of Pkg: $(($myData | Measure-Object -Property pkg -Average).Average)"
Write-Host "The avg of pp0: $(($myData | Measure-Object -Property pp0 -Average).Average)"
Write-Host "The avg of pp1: $(($myData | Measure-Object -Property pp1 -Average).Average)"
Write-Host "The avg of time: $(($myData | Measure-Object -Property time -Average).Average)"
  • Related