如何使用pandas找到一个未知大小的列中每3个值的平均值(平均值)。没有Numpy

问题描述 投票:-1回答:1

我试图弄清楚如何在CSV文件的不同值上应用这些函数(卑鄙.STD等)。为了简单起见,我在这里放一列的例子。

S08
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150

D1 = D.loc[:,'S08']

rang = len(D1)
for i in range(rang):
    x = D1.iloc[:,i+2]
    m = x.mean()
    print(m)


time    S08 S09 S15   S37   S38 S39   S41   S45 S49
1       10  5   100    5    145 1500    1   10  99
2       20  15  200    15   135 1400    2   150 99
3       30  25  300    25   125 1300    3   140 99
4       40  35  400    35   115 1200    4   130 99
5       50  45  500    45   105 1100    5   120 99
6       60  55  600    55   95  1000    6   110 99
7       70  65  700    65   85  900     7   100 99
8       80  75  800    75   75  800     8   90  99
9       90  85  900    85   65  700     9   80  99
10     100  95  1000   95   55  600     10  70  99
11     110  105 1100  105   45  500     11  60  99
12     120  115 1200  115   35  400     12  50  99
13     130  125 1300  125   25  300     13  40  99
14     140  135 1400  135   15  200     14  30  99
15     150  145 1500  145   5   100     15  20  99

enter image description here

pandas mean
1个回答
1
投票

使用由groupby地板划分的index除以3然后通过agg汇总列:

#create monotonic unique index (0,1,2...) if necessary
#df = df.reset_index(drop=True)
df = df.groupby(df.index // 3).agg({'col1':'mean', 'col2':'std'})

样品:

np.random.seed(100)
df = pd.DataFrame(np.random.randint(5, size=(10,3)), columns=list('ABC'))
print (df)
   A  B  C
0  0  0  3
1  0  2  4
2  2  2  2
3  2  1  0
4  0  4  3
5  4  2  0
6  3  1  2
7  3  4  4
8  1  3  4
9  4  3  3

df1 = df.groupby(df.index // 3).agg({'A':'mean', 'B':'std'})
print (df1)
          A         B
0  0.666667  1.154701
1  2.000000  1.527525
2  2.333333  1.527525
3  4.000000       NaN

#floor dicide index values for create triple groups
print (df.index // 3)
Int64Index([0, 0, 0, 1, 1, 1, 2, 2, 2, 3], dtype='int64')

编辑:

df1 = df.groupby(df.index // 3).agg(['mean','std'])
df1.columns = df1.columns.map('_'.join)
print (df1)

    A_mean     A_std    B_mean     B_std    C_mean     C_std
0  0.666667  1.154701  1.333333  1.154701  3.000000  1.000000
1  2.000000  2.000000  2.333333  1.527525  1.000000  1.732051
2  2.333333  1.154701  2.666667  1.527525  3.333333  1.154701
3  4.000000       NaN  3.000000       NaN  3.000000       NaN
© www.soinside.com 2019 - 2024. All rights reserved.