movie_id user_id rating
0 1 [5, 2, 1, 6] [4, 4, 5, 4]
1 2 [5, 1] [3, 3]
2 3 [1] [4]
3 4 [1] [3]
4 5 [1] [3]
5 6 [1] [5]
6 7 [6, 1] [2, 4]
7 8 [1, 6] [1, 4]
8 9 [1, 6] [5, 4]
我正在尝试获取“评级”中每行大于3的数字计数。例如,[4,4,5,5] => 4 / [3,3] => 0。
到目前为止,这是我所做的:
appr = df.copy()
appr['approval'] = appr['rating'].map(Counter)
appr
它输出:
movie_id user_id rating approval
0 1 [5, 2, 1, 6][4, 4, 5, 4] {4: 3, 5: 1}
1 2 [5, 1] [3, 3] {3: 2}
2 3 [1] [4] {4: 1}
3 4 [1] [3] {3: 1}
4 5 [1] [3] {3: 1}
5 6 [1] [5] {5: 1}
6 7 [6, 1] [2, 4] {2: 1, 4: 1}
7 8 [1, 6] [1, 4] {1: 1, 4: 1}
8 9 [1, 6] [5, 4] {5: 1, 4: 1}
我的目标是在每一行的“评级”中过滤不大于3的数字,并对它们的出现求和:
movie_id user_id rating approval appr_sum
0 1 [5, 2, 1, 6][4, 4, 5, 4] {4: 3, 5: 1} 4
1 2 [5, 1] [3, 3] {3: 2} 0
2 3 [1] [4] {4: 1} 1
3 4 [1] [3] {3: 1} 0
4 5 [1] [3] {3: 1} 0
5 6 [1] [5] {5: 1} 1
6 7 [6, 1] [2, 4] {2: 1, 4: 1} 1
7 8 [1, 6] [1, 4] {1: 1, 4: 1} 1
8 9 [1, 6] [5, 4] {5: 1, 4: 1} 2
我试过了 :
s = appr['rating'].map
t = [x for x in s if x > 3]
t
但是有一个
TypeError
:'method'对象是不可迭代的,并且如果这部分代码正确出现,则不会总结它们的出现。 最佳答案
将嵌套列表理解与过滤和sum
结合使用:
appr['appr_sum'] = [sum(v for k, v in x.items() if k > 3) for x in appr['approval']]
print (appr)
movie_id user_id rating approval appr_sum
0 1 [5, 2, 1, 6] [4, 4, 5, 4] {4: 3, 5: 1} 4
1 2 [5, 1] [3, 3] {3: 2} 0
2 3 [1] [4] {4: 1} 1
3 4 [1] [3] {3: 1} 0
4 5 [1] [3] {3: 1} 0
5 6 [1] [5] {5: 1} 1
6 7 [6, 1] [2, 4] {2: 1, 4: 1} 1
7 8 [1, 6] [1, 4] {1: 1, 4: 1} 1
8 9 [1, 6] [5, 4] {5: 1, 4: 1} 2
关于python - 如何过滤数据框列表中的数字(n> 3)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54403747/