【发布时间】:2018-03-08 09:20:54
【问题描述】:
在这段代码中,我有一个包含很多组合的数据 'a' 'b' 'c' 'd' 我试图找出每个组合存在的频率。(数据示例:abdc,abcc , abcd, abbb, aaaa, abdc,...) 之后,我希望得到每个字母组合的 0% 到 100% 的百分比答案。如果它为零。
示例输入:
letters: ['abc','aaa','abb','acc','aac','abc','bbb','ccc','ddd','abc','adc','acd','acd','aac','aad','bba','bab','abb','abc','abd'...]
我从这里得到 df:(tab_files 是获取我的数据的文件)
for i, tab_file in enumerate(tab_files):
df = pd.DataFrame.from_csv(tab_file, sep='\t')
这是我的尝试:
#letter_l = all combinations of letters (abcd) together
nt_l = "abcd"
letter_l = []
for i1 in nt_l:
for i2 in nt_l:
for i3 in nt_l:
letter = i1+i2+i3
letter_l.append(letter)
#print(letter_l)
#calculates the amount of each letter combination and shows the percentage
x = []
number_per_combination = {}
for b in letter_l:
counter = 0
number_per_combination[b] = 0
for c2 in df.letter:
if c2 == b:
counter +=1
number_per_combination[b] += 1
# amount of each letter combination divided through the whole amount
x.append(counter/(len(df.letter)))
但我得到奇怪的百分比作为答案......我不明白为什么。有人可以帮帮我吗?
Output I want: number_per combination
'abc': 20% (40)
'aaa': 10% (20)
'ccd': 0% (0)
'ddd': 3% (6)...
【问题讨论】:
-
你能提供任何样品吗?
-
df定义在哪里? -
这段代码试图实现什么?提供简单输入和预期输出。使用
itertools和Counter可以将整个代码重构为少于 5 行代码
标签: python