gpt4 book ai didi

python - Pandas :如何获得 Pandas 系列中最频繁的项目?

转载 作者:太空狗 更新时间:2023-10-29 21:20:32 24 4
gpt4 key购买 nike

如何获取 pandas 系列中出现次数最多的项目?

考虑系列 s

s = pd.Series("1 5 3 3 3 5 2 1 8 10 2 3 3 3".split()).astype(int)

返回值应该是3

最佳答案

你可以只使用pd.Series.mode并提取第一个值:

res = s.mode().iloc[0]

这不一定是低效的。与往常一样,使用您的数据进行测试,看看什么适合。

import numpy as np, pandas as pd
from scipy.stats.mstats import mode
from collections import Counter

np.random.seed(0)

s = pd.Series(np.random.randint(0, 100, 100000))

def jez_np(s):
_, idx, counts = np.unique(s, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
val = s[index]
return val

def pir(s):
i, r = s.factorize()
return r[np.bincount(i).argmax()]

%timeit s.mode().iloc[0] # 1.82 ms
%timeit pir(s) # 2.21 ms
%timeit s.value_counts().index[0] # 2.52 ms
%timeit mode(s).mode[0] # 5.64 ms
%timeit jez_np(s) # 8.26 ms
%timeit Counter(s).most_common(1)[0][0] # 8.27 ms

关于python - Pandas :如何获得 Pandas 系列中最频繁的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52038896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com