Python 矩阵 - 将矩阵限制在前 20 名

标签 python pandas

我有一个矩阵,用于计算我通过我创建的 DF 中的这段代码所做的两组学科之间的链接数:

new_df = df[['GrantRefNumber','Subject']]

a = ['Psychology','Education','Social policy','Sociology','Pol. sci. & internat. studies','Development studies','Social anthropology','Area Studies','Science and Technology Studies','Law & legal studies','Economics','Management & business studies','Human Geography','Environmental planning','Demography','Social work','Tools, technologies & methods','Linguistics','History']
final_df = new_df[new_df['Subject'].isin(a)]

ctrs = {location: Counter(gp.GrantRefNumber) for location, gp in final_df.groupby('Subject')}

ctrs = list(ctrs.items())
overlaps = [(loc1, loc2, sum(min(ctr1[k], ctr2[k]) for k in ctr1))
    for i, (loc1, ctr1) in enumerate(ctrs, start=1)
    for (loc2, ctr2) in ctrs[i:] if loc1 != loc2]
overlaps += [(l2, l1, c) for l1, l2, c in overlaps]

df2 = pd.DataFrame(overlaps, columns=['Loc1', 'Loc2', 'Count'])
df2 = df2.set_index(['Loc1', 'Loc2'])
df2 = df2.unstack().fillna(0).astype(int)

Matrix 长这样(很大所以拍了局部图:

enter image description here

我稍后在代码中将矩阵转换为和弦图,但想要一种方法来过滤(或移动到新的 DF)数据以仅显示前 20 个(或任何数字,以便我可以使用稍后变量)矩阵中的最高数字,然后将其他所有数字设为 0。

有没有简单的方法来做到这一点?

最佳答案

您可以使用:

df = pd.DataFrame({'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'D':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4]})

print (df)
   B  C  D  E
0  4  7  1  5
1  5  8  3  3
2  4  9  5  6
3  5  4  7  9
4  5  2  1  2
5  4  3  0  4

您可以先创建最高的唯一值,然后再创建 DataFrame.maskisin对于条件:

a = np.sort(np.unique(df.values.ravel()))[-3:]
print (a)
[7 8 9]


df = df.where(df.isin(a), 0)
print (df)
   B  C  D  E
0  0  7  0  0
1  0  8  0  0
2  0  9  0  0
3  0  0  7  9
4  0  0  0  0
5  0  0  0  0

关于Python 矩阵 - 将矩阵限制在前 20 名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46172220/

相关文章:

python - 诗歌在 macOS 12 上的哪里存储 virtualenvs?

python - 如何判断指定的文件是否位于指定的文件夹内?

python - 使用python从段落中提取文本

python - 具有较小数据框随机列的大型数据框(Pandas)

python - Pandas 修剪数据帧中的前导和尾随空格

python - 如何在 Pandas 数据框中对接近重复的值进行分组?

python - Pandas 数据框 - 根据后缀转换选定的单元格值

python - Pandas - 如何用 NaN 替换这些异常值

python:使用变量替换完全匹配

python - Pandas 掉落稀有元素