首页 > 解决方案 > 数据框中排列的Python平均值

问题描述

我正在尝试计算下面数据框中的每个排列f1的平均回报,但是我似乎无法让排列函数正常工作。f2(df)

          Date   f1   f2  return
0    1/01/2020  4.0  2.0  0.2895
1    2/01/2020  4.0  3.0  0.6504
2    3/01/2020  1.0  1.0  0.9887
3    4/01/2020  2.0  3.0  0.6141
4    5/01/2020  4.0  2.0  0.8520
5    6/01/2020  3.0  1.0  0.1124
6    7/01/2020  4.0  3.0  0.8104
7    8/01/2020  1.0  5.0  0.0890
8    9/01/2020  5.0  5.0  0.6954
9   10/01/2020  5.0  3.0  0.0554
10  11/01/2020  5.0  1.0  0.8025
11  12/01/2020  2.0  4.0  0.1666
12  13/01/2020  1.0  3.0  0.8451
13  14/01/2020  5.0  2.0  0.7373

我尝试了以下方法:

perm = itertools.permutations(df,2)

count_perm = []

for i in perm:
    count_perm.append(i)
    print(count_perm.index(i)+1,i)

print()
print('Number of permutations: ', len(count_perm)) 

我得到以下输出:

1 ('Date', 'f1')
2 ('Date', 'f2')
3 ('Date', 'return')
4 ('f1', 'Date')
5 ('f1', 'f2')
6 ('f1', 'return')
7 ('f2', 'Date')
8 ('f2', 'f1')
9 ('f2', 'return')
10 ('return', 'Date')
11 ('return', 'f1')
12 ('return', 'f2')

Number of permutations:  12

我正在寻找类似(示例)的输出:

Permutation     Avg. Return
(1,1)            0.40
(1,2)            0.23
(1,3)            0.12
...              ...
(5,5)            0.67

标签: pythonpandas

解决方案


另一种仅使用 gorupby 并创建元组列的方法......这会给你想要的输出吗?

a = df.groupby(['f1','f2'])['return'].mean().reset_index()
a['Permutation'] = list(zip(a['f1'].astype(int), a['f2'].astype(int)))
a = a[['Permutation', 'return']]
a

输出:

    Permutation return
0   (1.0, 1.0)  0.98870
1   (1.0, 3.0)  0.84510
2   (1.0, 5.0)  0.08900
3   (2.0, 3.0)  0.61410
4   (2.0, 4.0)  0.16660
5   (3.0, 1.0)  0.11240
6   (4.0, 2.0)  0.57075
7   (4.0, 3.0)  0.73040
8   (5.0, 1.0)  0.80250
9   (5.0, 2.0)  0.73730
10  (5.0, 3.0)  0.05540
11  (5.0, 5.0)  0.69540

推荐阅读