Python 计算表中有无因子的组合
我有一个类似于下面的表格,我想计算当前各种因素的不同组合。示例:全部存在的时间数(1表示存在,0表示不存在)。第一次缺席但有休息时间的次数,第二次缺席但有其他时间的次数,以及双打和三打缺席而有休息时间的次数 在shell中,检查所有存在的时间非常简单 awk'{如果($2==1)&($3==1)&($4==1)&($5==1)&($6==1))打印$1}所有的频率主题 但问题是计算所有可能存在的组合 该表如下所示:Python 计算表中有无因子的组合,python,perl,bash,bioinformatics,Python,Perl,Bash,Bioinformatics,我有一个类似于下面的表格,我想计算当前各种因素的不同组合。示例:全部存在的时间数(1表示存在,0表示不存在)。第一次缺席但有休息时间的次数,第二次缺席但有其他时间的次数,以及双打和三打缺席而有休息时间的次数 在shell中,检查所有存在的时间非常简单 awk'{如果($2==1)&($3==1)&($4==1)&($5==1)&($6==1))打印$1}所有的频率主题 但问题是计算所有可能存在的组合 该表如下所示: CEBP HEB TAL1 RUNX1 SPI1 1
CEBP HEB TAL1 RUNX1 SPI1
1 1 1 1 1
0 1 1 1 1
1 1 0 0 1
1 1 1 1 0
0 0 0 1 1
现在从这个表中产生了不同的组合
1所有人都在场的组合2第一个缺席,所有其他人都在场
3最后一位缺席,但其他人在场
4第三名和第四名缺席,但其他人在场
5前三名缺席,但其他人出席 在这样一个具有固定列数和n行数的表中,如何计算存在和不存在的组合 请帮忙
谢谢假设
数据
包含您的数据,这可以完成以下工作:
with open("data") as f:
lines=[line.strip().split() for line in f]
combinations={}
for combination in lines[1:]:
key=", ".join([lines[0][i]
for i in xrange(len(combination))
if combination[i] != '0'])
combinations[key]=combinations.setdefault(key, 0)+1
for key, value in combinations.iteritems():
print value, '\t', key
或者,使用“集合”模块:
import collections
with open("data") as f:
lines=[line.strip().split() for line in f]
combinations=collections.Counter(
", ".join(lines[0][i]
for i in xrange(len(combination))
if combination[i] != '0')
for combination in lines[1:])
for key, value in combinations.iteritems():
print value, '\t', key
编辑:另一个版本使用生成器表达式保存资源
import collections
with open("data") as f:
lines=(line.strip().split() for line in f)
header=next(lines)
combinations=collections.Counter(
", ".join(header[i]
for i in xrange(len(combination))
if combination[i] != '0')
for combination in lines)
for key, value in combinations.iteritems():
print value, '\t', key
我相信这是可以改进的。比hochi的解决方案更长,但它的工作原理可能更清晰:
with open("data") as f:
next(f) # Skip header row
lines=[[int(n) for n in x.strip().split()] for x in f if x.strip()]
count = 0
for row in lines:
if all(row):
count += 1
print "All present:", count
count = 0
for row in lines:
if (not row[0]) and all(row[1:]):
count += 1
print "All except first column are 1:", count
我不会做所有的例子,但这应该给你一个想法。一个Perl程序,它可以像计算二进制数一样计算所有的组合。我重复了几行,以确保计数有效
use strict;
use warnings;
use Bit::Vector;
# CEBP HEB TAL1 RUNX1 SPI1
my @factors = (
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 1, 1, 1, 1],
[1, 1, 0, 0, 1],
[1, 1, 1, 1, 0],
[0, 0, 0, 1, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 1, 1],
);
my %combo;
for my $row (@factors) {
my $v = Bit::Vector->new_Bin(32, join('', @$row))->to_Dec;
$combo{$v}++;
}
for my $v (sort keys %combo) {
printf "Result: %3d %5s Count: %d\n",
$v,
Bit::Vector->new_Dec(5, $v)->to_Bin,
$combo{$v}
;
}
输出:
Result: 15 01111 Count: 1
Result: 25 11001 Count: 1
Result: 3 00011 Count: 3
Result: 30 11110 Count: 1
Result: 31 11111 Count: 3
你能展示一下你试过的代码吗?因此,答案可以更好地融入其中,并试图帮助您?这不仅仅是一个按所有列分组的选择计数(*)吗?这不计算每个组合存在的时间。