在Powershell [MATH]函数中遍历单元格

时间:2015-12-08 18:10:16

标签: csv powershell math standard-deviation

我正在尝试使用[MATH]计算PowerShell中的一些基本统计信息,特别是名为“td”的字段中一组值的标准偏差。

我的代码目前输出的数字太高而不能成为标准偏差。例如,如果列中的值没有范围(所有值均为15),标准偏差应为零,则返回值等于15.

我认为这可能与在此部分代码中错误使用$Y有关:

Foreach ($Y in $STDEVInputFile) {
$DevMath += [math]::pow(($STDEVInputFile[$Y].td - $STDEVAVG.Average), 2)

但是,我对PowerShell的熟悉程度还不够。那里的任何人都能告诉我哪里出错了吗?这是完整的代码:

##################################################
#Calculate statistics for TD column in each file

$i = 1

While ($i -le 211) {

#Set the variable to the filename with the iteration number
$filename = "c:\zMFM\z550Output\20dSummer\fixed20dSum550Output$i.csv"


#Check to see if that a file with $filename exists. If not, skip to the next iteration of $i. If so, run the code to collect the statistics for each variable and output them each to a different file
If (Test-Path $filename) {

#Calculate the Standard Deviation
#First get the average of the values in the column
$STDEVInputFile = Import-CSV $filename

#Find the average and count for column 'td'
$STDEVAVG = $STDEVInputFile | Measure-Object td -Average | Select Count, Average
$DevMath = 0

$Y = 

# Sum the squares of the differences between each value in the field and the mean 
Foreach ($Y in $STDEVInputFile) {
$DevMath += [math]::pow(($STDEVInputFile[$Y].td - $STDEVAVG.Average), 2)

#Divide by the number of samples minus one
$STDEV = [Math]::sqrt($DevMath / ($STDEVAVG.Count-1))

}

#Calculate the basic statistics for column 'td' with the MEASURE-OBJECT cmdlet
$STATS = Import-CSV $Filename |
Measure-Object td -ave -max -min |

#Export the statistics as a CSV
Export-CSV -notype "c:\zMFM\z550Output\20dSummer\tempstats$i.csv"

#Store the values that will go into the final table as variables
$GetColumns = Import-CSV $filename
$VZA = $GetColumns[0].VZA
$VAZ = $GetColumns[0].VAZ


#Import the temporary stats file, append columns and populate them with the declared variables

Import-Csv "c:\zMFM\z550Output\20dSummer\tempstats$i.csv" |
  Select-Object @{Name="VZA";Expression={$VZA}},
                @{Name="VAZ";Expression={$VAZ}},
                @{Name="STDDEV";Expression={$STDEV}},
                Count, Average, Maximum, Minimum, Property |


#Export the $STATS file containing everything you need in the correct folder


Export-CSV -notype "c:\zMFM\z550Output\20dSummer\Statistics_TD_20dSum550_$i.csv"

}
$i++
}

1 个答案:

答案 0 :(得分:2)

I think:

ng-repeat

should be

$DevMath += [math]::pow(($STDEVInputFile[$Y].td - $STDEVAVG.Average), 2)

The original $DevMath += [math]::pow(($Y.td - $STDEVAVG.Average), 2) part is going to return null/0, so for your example of all 15s in the input, instead of each step doing 15-15=0 squared, you are doing 0-15 = -15 squared.


You may also want to get rid of the $Y= empty line before the foreach loop, as it is(maybe) setting $Y to the output of the whole loop, and if nothing else using that while using $Y inside the loop is confusing.