Python 数据帧中的数字频率
我有这样一个数据集(numeros): 我想得到所有列中最频繁的数字 我试过了Python 数据帧中的数字频率,python,pandas,numpy,Python,Pandas,Numpy,我有这样一个数据集(numeros): 我想得到所有列中最频繁的数字 我试过了 #through all the columns for i in numeros[:16]: print(numeros[i].value_counts().idxmax()) 它的回归 1,7,12,5,8,17,14,9,20,2,6,4,14,2,21 但这只返回每列中最频繁的数字,对吗? 考虑到我所有的数据集,我如何获得最频繁的15个数字?使用集合。计数器及其最常用的方法: from collecti
#through all the columns
for i in numeros[:16]:
print(numeros[i].value_counts().idxmax())
它的回归
1,7,12,5,8,17,14,9,20,2,6,4,14,2,21
但这只返回每列中最频繁的数字,对吗?
考虑到我所有的数据集,我如何获得最频繁的15个数字?使用
集合。计数器及其最常用的方法:
from collections import Counter
df = pd.DataFrame(np.random.randint(0, 100, (100, 100)))
res = pd.DataFrame.from_dict(Counter(df.values.flatten()).most_common(15))
print(res)
0 1
0 64 126
1 72 119
2 1 116
3 14 115
4 28 114
5 67 113
6 16 113
7 56 113
8 84 112
9 3 112
10 19 112
11 13 111
12 94 110
13 52 110
14 66 109
使用collections.Counter
及其最常用的方法:
from collections import Counter
df = pd.DataFrame(np.random.randint(0, 100, (100, 100)))
res = pd.DataFrame.from_dict(Counter(df.values.flatten()).most_common(15))
print(res)
0 1
0 64 126
1 72 119
2 1 116
3 14 115
4 28 114
5 67 113
6 16 113
7 56 113
8 84 112
9 3 112
10 19 112
11 13 111
12 94 110
13 52 110
14 66 109
解决方案:
df = pd.DataFrame(np.random.randint(1,100,(9,15)))
df = df.stack().to_frame('key')
df['value'] = 1
df.groupby('key').count().sort_values(['value'],ascending=False).iloc[:15]
解决方案:
df = pd.DataFrame(np.random.randint(1,100,(9,15)))
df = df.stack().to_frame('key')
df['value'] = 1
df.groupby('key').count().sort_values(['value'],ascending=False).iloc[:15]
使用:
结果将是一系列首先计数最高的计数,并使用数据帧值进行索引。使用:
结果将首先是一系列计数最高的计数,并用数据帧值进行索引。为什么要在末尾添加.idmax()
?@Fozoro获取数字,而不是计数为什么要在末尾添加.idmax()
?@Fozoro获取数字,而不是计数