在这段代码中,我有一个包含来自'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)...
答案 0 :(得分:0)
那么你要做的是直方图?这是一个简单的方法:
input_list = ['a', 'a', 'b', 'b', 'b', 'c']
def histogram(my_list):
result = {}
for item in my_list:
result[item] = result.get(item, 0) + 1
return result
print(str(histogram(input_list)))
.get()方法从字典中返回给定键的值。如果密钥不存在,则插入并给出第二个参数中提供的值。
答案 1 :(得分:0)
import re
import itertools
data="aaa, abc, aab"
words = re.split(', ',data)
words_count = {}
total_count = len( words )
for word in list(itertools.product(["a","b","c","d"], repeat=3)):
words_count["".join(word)] = 0
for word in words:
words_count[word] = words_count.get(word,0) + 1
for word in words_count:
p = words_count[word]/total_count * 100
print( "%s: %.3f%%\t(%d)" % (word,p,words_count[word]) )