python - 数据框中排列的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
解决方案
另一种仅使用 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
推荐阅读
- amazon-eks - 通过 aws cli - 我如何获得创建 eks 集群的实体的 arn?
- css - 防止内容增加 CSS 网格列的大小
- css - 如何水平对齐按钮和ul元素
- linux - 如何为 BASH 垃圾箱脚本添加选项?
- scala - 在 Akka 中创建演员的首选方式是什么?
- windows-10 - 不全屏播放幻灯片的窗口的图像查看器
- python - 字符串列表或单个字符串中的命名元组之间的区别?
- spring-boot - Spring Boot 存储库测试无法加载应用程序上下文
- python - 如果 Python2 在 .py 文件上运行时由于语法错误(.py 文件包含 f 字符串)而失败,则尝试显示自定义错误
- laravel - Laravel 中具有不同列值的 CASE 排序不起作用