这是在计算共现频率时出现的问题。
我有一个数据框,它的884x884矩阵的行和列对称。
我想从此矩阵的元素中提取前20个值。
但是,如果我对列或行进行排序,则只有一个列或行会做出反应。 请帮助我
alexa actual afford alarm alway dot ask app amazon
alexa 0 9 4 7 7 49 30 10 17
actual 9 0 2 2 1 26 6 1 0
afford 4 2 0 0 0 3 1 0 0
alarm 7 2 0 0 0 15 10 4 1
alway 7 1 0 0 0 3 0 4 0
dot 49 26 3 15 3 0 42 16 25
ask 30 6 1 10 0 42 0 6 11
app 10 1 0 4 4 16 6 0 6
amazon 17 0 0 1 0 25 11 6 0
这是示例数据框
也许我想提取前2个值,
输出:((alexa,dot),49),((dot,ask),42)
答案 0 :(得分:1)
尝试一下;尽管我敢肯定有更优雅的方法可以做到这一点。
使用如上所述的DataFrame(称为df
)
import itertools
import pandas as pd
# Create a list of unique combinations (e.g. (alexa, actual)).
groups = list(itertools.combinations(df.columns, 2))
# Collect the count for each combination.
data = [('_'.join(group), df.loc[group]) for group in groups]
# Populate a new DataFrame with the counts and sort.
dfx = (pd.DataFrame(data, columns=['group', 'count'])
.sort_values('count', ascending=False)
.reset_index(drop=True))
# Display the top (n) values.
dfx.head(5)
group count
0 alexa_dot 49
1 dot_ask 42
2 alexa_ask 30
3 actual_dot 26
4 dot_amazon 25
希望这会有所帮助!