【问题标题】:numpy method instead of fornumpy 方法而不是 for
【发布时间】:2021-12-17 07:37:23
【问题描述】:

我有一个如下所示的 pandas 数据框(黄色突出显示表示列的示例共现):

我需要形成一个矩阵,其中元素是整个数据帧中列的共现之和

例如,我想要的矩阵中的element(i,j) 表示ij 列都是1 的次数(在上图中突出显示)。

我已经写了这段代码,但这不是一个好方法……谁能帮我用 numpy(或其他有效的方法)写代码

######## co-occurrence of tags
co_occur=np.zeros(25*25)
co_occur=co_occur.reshape(25,25)
def co_occurance(i,j):
    k=0
    for index,row in train_data.iterrows():
        if row.iloc[i+2]==1:
            if row.iloc[j+2]==1:
                k+=1
    return k

for i in range(1,25):
    for j in range(i+1,25):
        co_occur[i,j]=co_occurance(i,j)

25 是列数。

【问题讨论】:

  • 我认为找到groups 每行的非零值索引非常容易。完成后,has been discussed 很久以前似乎是一个相当复杂的问题。如果您擅长循环,请使用numba 对其进行优化。否则,您会遇到np.concatenate([combinations(g, 2) for g in groups]) 类型的问题,这是可以解决的,导致解决方案非常复杂。您是否有任何关于每行最大非零值数量的其他信息?
  • 欢迎来到 SO!请不要将数据或代码添加为图像。而是使用纯文本或更好的方法,提供一段构建数据框的代码。这将更有可能有人能够快速帮助您。

标签: python algorithm numpy


【解决方案1】:

如果你可以在纯 numpy 中做到这一点,我不知道该怎么做。但无论如何这是我的解决方案

from itertools import permutations

co_occur=np.zeros((25,25))

# get all rows where sum>1
rows=np.where(np.sum(train_data,1)>1)
for row in rows[0]:
    # get all indices of columns with value=1
    idx=np.where(train_data[row]==1)
    # and add +1 in every combination of indices
    for comb in permutations(idx[0],r=2):
        co_occur[comb]+=1

【讨论】:

    猜你喜欢
    • 2016-02-20
    • 2019-08-22
    • 2019-02-05
    • 2021-02-24
    • 2017-06-27
    • 2019-03-21
    • 2023-01-26
    • 2018-01-08
    • 2018-07-06
    相关资源
    最近更新 更多