Python 3.x Python:根据每个项的最高出现频率创建数据帧

Python 3.x Python:根据每个项的最高出现频率创建数据帧,python-3.x,dataframe,count,frequency,Python 3.x,Dataframe,Count,Frequency,我有一个数据帧,如下所示 data = { 'Code': ['P', 'J', 'M', 'Y', 'P', 'Z', 'P', 'P', 'J', 'P', 'J', 'M', 'P', 'Z', 'Y', 'M', 'Z', 'J', 'J'], 'Value': [10, 10, 20, 30, 10, 40, 50, 10, 10, 20, 10, 50, 60, 40, 30, 20, 40, 20, 10] } example = pd.DataFrame(dat

我有一个数据帧,如下所示

data = {
    'Code': ['P', 'J', 'M', 'Y', 'P', 'Z', 'P', 'P', 'J', 'P', 'J', 'M', 'P', 'Z', 'Y', 'M', 'Z', 'J', 'J'],
    'Value': [10, 10, 20, 30, 10, 40, 50, 10, 10, 20, 10, 50, 60, 40, 30, 20, 40, 20, 10]
}

example = pd.DataFrame(data)
使用Python3,我想从数据帧
示例
中创建另一个数据帧,以便获得与更多相关联的代码

新的数据帧应该与下面的解决方案类似

output = {'Code': ['J', 'M', 'Y', 'Z', 'P', 'M'],'Value': [10, 20, 30, 40, 50, 50]}

solution = pd.DataFrame(output)

可以看出,与其他代码相比,J与值10的关联性更强,因此选择了J,依此类推。

您可以定义一个函数,返回出现次数最多的项,并将其应用于分组的元素。最后分解为列表到行

>>> def most_occurring(grp):
...     res = Counter(grp)
...     highest = max(res.values())
...     return  [k for k, v in res.items() if v == highest]
... 
>>> example.groupby('Value')['Code'].apply(lambda x: most_occurring(x)).explode().reset_index()
   Value Code
0     10    J
1     20    M
2     30    Y
3     40    Z
4     50    P
5     50    M
6     60    P

如果我理解正确,你需要这样的东西:

grouped = example.groupby(['Code', 'Value']).indices
arr_tmp = []
[arr_tmp.append([i[0], i[1], len(grouped[i])]) for i in grouped]#['Int64Index'])
output = pd.DataFrame(data=arr_tmp, columns=['Code', 'Value', 'index_count'])
output = output.sort_values(by=['index_count'], ascending=False)
output.reset_index(inplace=True)
output