Suk*_*djf 1 python dictionary frequency dataframe pandas
我有一个数据帧熊猫含有3列id1,id2,call_freq其中,所述数据是以下形式
输入:
id1 id2 call_frequency
1 1 2
1 1 3
1 1 3
1 1 3
1 1 3
1 2 5
1 2 5
1 2 4
2 1 9
2 2 6
2 2 6
2 2 7
2 2 7
2 2 7
2 2 7
Run Code Online (Sandbox Code Playgroud)
输出:
call_frequency_dict列应包含一个字典字符串,其中call_frequency中的元素用于id1和id2和及其频率的组合作为值。
我尝试搜索,但没有发现任何帮助。如何获得call_frequency_dict?
我建议使用value_counts而不是将这些类型的数据推送到dict
df.groupby(['id1','id2']).call_frequency.value_counts()
Run Code Online (Sandbox Code Playgroud)
匹配您的输出
import collections
df.groupby(['id1','id2']).call_frequency.agg(collections.Counter).reset_index()
Out[55]:
id1 id2 call_frequency
0 1 1 {2: 1, 3: 4}
1 1 2 {5: 2, 4: 1}
2 2 1 {9: 1}
3 2 2 {6: 2, 7: 4}
Run Code Online (Sandbox Code Playgroud)