【发布时间】:2018-04-09 10:12:56
【问题描述】:
这里我有一个由列表启动的代码,它需要两个随机字母并将它们放回主列表。然后我计算每个生成列表中的每个字母:
import random
import collections
def randMerge(l:list, count:int) -> list:
return l + [random.sample(l,k=count)]
def flatten(d):
return [i for b in [[c] if not isinstance(c, list) else flatten(c)
for c in d] for i in b]
num = 2
aList = ['A','B','C','D']
newList = aList[:]
for _ in range(3):
newList = randMerge(newList,num)
print(newList)
new_counts = collections.Counter(flatten(newList))
print(new_counts)
给出:
['A', 'B', 'C', 'D', ['A', 'C']]
Counter({'A': 2, 'C': 2, 'B': 1, 'D': 1})
['A', 'B', 'C', 'D', ['A', 'C'], ['D', 'A']]
Counter({'A': 3, 'C': 2, 'D': 2, 'B': 1})
['A', 'B', 'C', 'D', ['A', 'C'], ['D', 'A'], ['A', 'B']]
Counter({'A': 4, 'B': 2, 'C': 2, 'D': 2})
现在我想知道如何制作一个数据框,使每列计数器中的数字和行代表字母。我这样做了:
df = pandas.DataFrame.from_dict(new_counts, orient='index')
但这只给了我最后一个计数器。另外,如何制作每个计数器的直方图并将它们一起显示?
【问题讨论】:
标签: python python-3.x pandas dataframe histogram