![](/img/trans.png)
[英]How count the number of occurrences of all the values in a dictionary in python? TypeError: unhashable type: 'list'
[英]Count the number of occurrences for values dictionary list python
我想在我的字典中獲得值的出現次數:
test = {
"Staph": ["grp1","grp2","grp3"],
"Lacto": ["grp2","grp3","grp4","gr5"],
"Bacilus": ["grp2","grp4","grp6"]
}
我想為我的鑰匙獲取公共組,例如:
grp1 只在 Staph 中,所以 grp1 = 1 和 grp2 在“Staph”和“Lacto”和“Bacillus”中,所以 grp2 = 3
grp1 = 1 , grp2 = 3 , grp3 = 2, grp4 = 2 , grp5 = 1, grp6 = 1
之后,我想計算我的先例數字出現的次數,例如:
我有 grp1 = 1 和 grp5 = 1 和 grp6 = 1 所以只有一個鍵中有 1 組的次數是 3 或者如果我取 grp3 = 2 , grp4 = 2 有 2 個相同組的次數對於不同的鍵是 2
所以我想要這樣的結果:
number : the number of times n groups appear in different keys
Staph grp1 grp2 grp3
Lacto grp2 grp3 grp4 grp5
Bacillus grp2 grp4 grp6
1 3 2 2 1 1
number_of_1 = 3
number_of_2 = 2
number_of_3 = 1
希望你已經明白,謝謝你的回答
你去吧:)
test = {
"Staph": ["grp1","grp2","grp3"],
"Lacto": ["grp2","grp3","grp4","gr5"],
"Bacilus": ["grp2","grp4","grp6"]
}
groups = set()
for i,j in test.items():
for k in j:
groups.add(k)
counts = []
new_test = {}
for k in groups:
for i in test.keys():
if k in test[i]:
if k not in new_test:
new_test[k] = 1
else:
new_test[k] += 1
print(new_test)
values = [i for i in new_test.values()]
values_set = set(values)
count_values = []
for i in values_set:
count = 0
for j in values:
if i == j:
count += 1
count_values.append([i,count])
print(count_values)
您可以使用Counter()
實現來進一步簡化代碼
test = {
"Staph": ["grp1","grp2","grp3"],
"Lacto": ["grp2","grp3","grp4","gr5"],
"Bacilus": ["grp2","grp4","grp6"]
}
from collections import Counter
grp_counter = Counter()
for k, v in test.items():
grp_counter.update(Counter(v))
print(grp_counter)
請執行下列操作:
import pandas as pd
test = {
"Staph": ["grp1", "grp2", "grp3"],
"Lacto": ["grp2", "grp3", "grp4", "grp5"],
"Bacilus": ["grp2", "grp4", "grp6"]
}
# prepare data
all_values = sorted(set().union(*test.values()))
data = {key: [val if val in values else None for val in all_values] for key, values in test.items()}
# construct dataframe from data
df = pd.DataFrame.from_dict(data,orient="index")
# compute counts
row = df.notna().sum().T
row.name = "Counts"
# append counts as a new row
res = df.append(row).fillna("")
print(res)
輸出
0 1 2 3 4 5
Staph grp1 grp2 grp3
Lacto grp2 grp3 grp4 grp5
Bacilus grp2 grp4 grp6
Counts 1 3 2 2 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.