PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 26, 2022

[FIXED] how to caculate the avg of column from a csv which does not have headers with powershell?

 August 26, 2022     csv, powershell     No comments   

Issue

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?


Solution

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)"


Answered By - Guy S
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing