从各种计数器制作表格和直方图

时间:2018-04-09 10:12:56

标签: python python-3.x pandas dataframe histogram

这里我有一个由列表启动的代码,它需要两个随机字母并将它们放回主列表中。然后我计算每个生成列表中的每个字母:

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')

然而这只给了我最后一个柜台。另外,我如何制作每个计数器的直方图并将它们一起显示?

1 个答案:

答案 0 :(得分:0)

如果您需要每列代表Counter对象的内容,您可以从对象列表创建数据框,然后进行转置。

import collections, random, pandas as pd

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']

res = []
newList = aList[:]

for _ in range(3):
    newList = randMerge(newList,num)
    new_counts = collections.Counter(flatten(newList))
    res.append(new_counts)

print(res)

# [Counter({'A': 2, 'C': 2, 'B': 1, 'D': 1}),
#  Counter({'C': 3, 'A': 2, 'D': 2, 'B': 1}),
#  Counter({'C': 4, 'A': 2, 'B': 2, 'D': 2})]

df = pd.DataFrame(res).T

print(df)

#    0  1  2
# A  2  2  2
# B  1  1  1
# C  2  3  5
# D  1  2  3