【问题标题】:Calculate percentages in Python (0% to100%)在 Python 中计算百分比(0% 到 100%)
【发布时间】: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 定义在哪里?
  • 这段代码试图实现什么?提供简单输入和预期输出。使用 itertoolsCounter 可以将整个代码重构为少于 5 行代码

标签: python


【解决方案1】:

所以你想要做的是一个直方图?这是一个简单的方法:

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() 方法从字典中返回给定键的值。如果键不存在,则将其插入并给出第二个参数中提供的值。

【讨论】:

    【解决方案2】:
    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]) )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-13
      • 2014-08-23
      • 1970-01-01
      • 2020-06-25
      • 2022-01-26
      • 1970-01-01
      • 2022-11-15
      • 2011-06-01
      相关资源
      最近更新 更多