Skip to main content
 首页 » 编程设计

python之Count 满足条件的序列总数,没有for循环

2024年10月01日7lyhabc

我有以下数据框作为输入:

l = [2,2,2,5,5,5,3,3,2,2,4,4,6,5,5,3,5] 
df = pd.DataFrame(l) 
print(df) 
    0 
0   2 
1   2 
2   2 
3   5 
4   5 
5   5 
6   3 
7   3 
8   2 
9   2 
10  4 
11  4 
12  6 
13  5 
14  5 
15  3 
16  5 

作为输出,我希望得到满足特定条件的总序列的最终计数。例如,在这种情况下,我想要值大于 3 的序列数。 所以,输出是 3。

  • 第一个序列 = [555]
  • 第二个序列 = [44655]
  • 第三个序列 = [5]

有没有一种方法可以在没有 pandas 中的 for 循环的情况下进行计算? 我已经使用 for-loop 实现了一个解决方案,我想知道是否有更好的方法在 O(N) 时间内使用 pandas。

非常感谢!

与此问题相关:How to count the number of time intervals that meet a boolean condition within a pandas dataframe?

请您参考如下方法:

您可以使用:

m = df[0] > 3 
df[1] = (~m).cumsum() 
df = df[m] 
print (df) 
    0  1 
3   5  3 
4   5  3 
5   5  3 
10  4  7 
11  4  7 
12  6  7 
13  5  7 
14  5  7 
16  5  8 
 
 
#create tuples 
df  = df.groupby(1)[0].apply(tuple).value_counts() 
print (df) 
 
(5, 5, 5)          1 
(4, 4, 6, 5, 5)    1 
(5,)               1 
Name: 0, dtype: int64 

#alternativly create strings 
df  = df.astype(str).groupby(1)[0].apply(''.join).value_counts() 
print (df) 
 
5        1 
44655    1 
555      1 
Name: 0, dtype: int64 

如果需要输出为列表:

print (df.astype(str).groupby(1)[0].apply(''.join).tolist()) 
['555', '44655', '5'] 

详细信息:

print (df.astype(str).groupby(1)[0].apply(''.join)) 
 
3      555 
7    44655 
8        5 
Name: 0, dtype: object