繁体   English   中英

如何编写“for循环”来计算csv中列的统计信息?

[英]How to write a “for loop” to calculate statistical information about columns in csv?

我有几个需要从中提取数据的数据文件,我想实现一个 for 循环来有效地执行此操作。 对于每个数据文件,我需要计算每一列的平均值和标准差。 请注意,每个数据文件都有不同的行数和列数,但第一行始终表示列号(见下图)。 在找出每列的平均值和标准偏差后,我希望它告诉我哪些列的平均值/标准偏差最大和最小。

为了说明这里是一些数据:

0           1           2           3
105         154         148         138
74          62          32          178
44          16          156         100
83          19          16          66

这是所需的 output

Stats for "filename.csv"

           0           1           2           3
Mean       76.5        62.8        88          120.5
Sd         21.9        55.7        64.31       41.8


Smallest Mean - Column "1"
Largest Mean - Column "3
Smallest Sd - Column "0"
Largest Sd - Column "2"
``

我在这里使用过 pandas。

In [15]: import pandas as pd

In [16]: df = pd.read_csv("a.csv")

In [17]: df
Out[17]:
     0    1    2    3
0  105  154  148  138
1   74   62   32  178
2   44   16  156  100
3   83   19   16   66

In [18]: combined = pd.concat([df.mean(), df.std()], axis=1).T

In [19]: combined.index = ["Mean", "Std"]

In [20]: combined
Out[20]:
              0          1          2           3
Mean  76.500000  62.750000  88.000000  120.500000
Std   25.278449  64.360314  74.260802   48.314939

为了得到最大值和最小值:

In [40]: print(f'Smallest Mean - Column {combined[combined.index == "Mean"].idxmin(axis=1)[0]}')
Smallest Mean - Column  1

In [41]: print(f'Largest Mean - Column {combined[combined.index == "Mean"].idxmax(axis=1)[0]}')
Largest Mean - Column  3

In [42]: print(f'Largest Std - Column {combined[combined.index == "Std"].idxmax(axis=1)[0]}')
Largest Std - Column  2

In [43]: print(f'Smallest Std - Column {combined[combined.index == "Std"].idxmin(axis=1)[0]}')
Smallest Std - Column 0

均值和标准差数组


import numpy as np  # linear algebra

data = [[0, 1, 2, 3],
        [105,154, 148, 138],
        [74, 62, 32, 178],
        [44, 16, 156, 100],
        [83, 19, 16, 66]]
data = np.array(data) # transform a list into an numpy array, for best data manipulation
data = data[1:,:] #get all the rows starting from the second (0,1,2,...) so the first is removed
data = data.T #transpose de matrix

mean_std = [ [np.mean(x), np.std(x)] for x in data ]

这段代码的作用是

  • 数据最初是一个列表,所以我通过np.array从 numpy 库中调用一个方法,该方法将数据转换为另一个 object,它具有一些已经内置的函数,我将使用它们
  • 第一行被删除
  • 数据被转置是因为,正如您在data初始化中所见,它是一个列表列表,其中二级列表相当于一行。 使用data.T允许我使用下一个代码并按列应用它
  • 这段代码更棘手。 for x in data data的每个元素(即表的列)执行某些操作相同。 此元素保存为x [np.mean(x), np.std(x)] 此语句将 function np.meannp.std应用于每个x元素,并将结果保存在列表中。 所有这些meansstd列表都保存到另一个列表中。 这就是语句外部括号的原因

寻找结果


mean = np.array(mean_std).T[0]
std = np.array(mean_std).T[1]
position = np.array(range(0, len(std)))
position[ std == max(std) ]
  • 将矩阵分成两个 arrays。 一个是平均值,另一个是标准差。
  • 它创建了一个 position 数组
  • 使用此数组以获取满足条件的位置,在本例中为 max。 在这种情况下是 2(第三列)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM