Python中的成对频率计数表

1 投票
2 回答
1227 浏览
提问于 2025-04-17 20:47

我刚接触Python,大部分工作都是在R语言中完成的。我想知道如何在Python中实现这个问题。请参考这个链接,以便更清楚地理解问题和R语言的解决方案代码。 如何从长格式数据框计算成对计数表

这是数据集:

id  featureCode
5   PPLC
5   PCLI
6   PPLC
6   PCLI
7   PPL
7   PPLC
7   PCLI
8   PPLC
9   PPLC
10  PPLC

这是我想要的结果:

     PPLC  PCLI  PPL
PPLC  0     3     1
PCLI  3     0     1
PPL   1     1     0

我想计算每个特征代码与其他特征代码一起使用的次数(标题中的“成对计数”)。希望这样说能让你明白。请帮帮我。谢谢!

2 个回答

0

这里有一种在Pandas中处理这个问题的方法,它使用的数据框(DataFrame)和R语言类似。我假设你已经有一个名为 df 的数据框,里面包含了你的数据。(你可以通过使用 pandas.read_table 从文件中读取数据。具体可以参考这个链接: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_table.html)。

首先,使用 groupby 按照 id 对列进行分组。

gps = df.groupby("id")
print gps.groups
Out: {5: [0, 1], 6: [2, 3], 7: [4, 5, 6], 8: [7], 9: [8], 10: [9]}

groups 会给出属于同一个 id 的行号。

接下来,你需要创建一个目标矩阵,这个矩阵的行和列名称是你 featureCode 中的唯一值。

unqFet = list(set(df["featureCode"]))
final = pandas.DataFrame(columns=unqFet, index=unqFet)
final = final.fillna(0)
print final
Out: 
            PCLI PPLC PPL
     PCLI    0    0   0
     PPLC    0    0   0
     PPL     0    0   0

最后,遍历你的分组,并在你的 final 矩阵中增加正确的值。

for g in gps.groups.values():
    for i in range(len(g)):
       for j in range(len(g)):
          if i != j:
              final[ df["featureCode"][g[i]] ][ df["featureCode"][g[j]] ] += 1

print final
Out:
          PCLI PPLC PPL
   PCLI    0    3   1
   PPLC    3    0   1
   PPL     1    1   0
1

这个可以通过设置一个字典来实现,使用集合和计数器来进行分析。不过,我会展示一个使用最简单的字典和循环方法的分析。当然,实际的代码可以写得更简洁,我故意展示了一个扩展版。我的Python环境没有Pandas库,所以我使用的是最基础的Python。

# Assume the you have a set of tuples lst
lst.sort() # sort the list by id
mydict = {}
id = None
tags = []
for ids in lst:
  if ids[0] == id
    # Pick up the current entry
    tags.append(ids[1])
  else:
    # This is a new id
    # check the count of the previous tags.
    for elem1 in tags:
      for elem2 in tags:
        if elem1 != elem2:
          if elem1 not in mydict:
            mydict[elem1] = {}
          if elem2 not in mydict[elem1]:
            mydict[elem1][elem2] = 0
          mydict[elem1][elem2] += 1
    # This is a different id, reset the indicators for the next loop
    id = ids[0]
    tags = ids[1]        # This is a new id
else:
  # The last element of the lst has to be processed as well
  # check the count of the previous tags.
  for elem1 in tags:
    for elem2 in tags:
      if elem1 != elem2:
        if elem1 not in mydict:
          mydict[elem1] = {}
        if elem2 not in mydict[elem1]:
          mydict[elem1][elem2] = 0
        mydict[elem1][elem2] += 1


# at this point, my dict has the full dictionary count
for tag in mydict.keys():
  print tag, mydict[tag]

现在,这样就得到了带有计数的标签,你可以通过遍历最终的字典来格式化输出,适当地打印出键和计数。

撰写回答