字典值以excel列

时间:2018-03-19 20:47:44

标签: python pandas dictionary

我想将键值对的字典转换为excel文件,其列名与相应列的值匹配。

例如:

我有一个excel文件,其列名为:

a,b,c,d,e,f,g and h.

我有一本字典:     {1:['c','d'],2:['a','h'],3:['a','b','b','f']}

我需要输出:

       a  b  c  d  e  f  g  h

1            1  1                

2      1                    1

3      1  2           1  

1,2,3是字典中的键。 其余列可以是0null

我试过拆分字典并且正在

1 = ['c','d']
2 = ['a','h']
3 = ['a','b','b','f']

但是,我不知道如何传递它以匹配excel文件。

2 个答案:

答案 0 :(得分:0)

您的问题可以通过pandascollections来解决(可能存在更有效的解决方案):

import pandas as pd
from collections import Counter
d = {...} # Your dictionary
series = pd.Series(d) # Convert the dict into a Series
counts = series.apply(Counter) # Count items row-wise
counts = counts.apply(pd.Series) # Convert the counters to Series
table = counts.fillna(0).astype(int) # Fill the gaps and make the counts integer
print(table)
#   a  b  c  d  f  h
1  0  0  1  1  0  0
2  1  0  0  0  0  1
3  1  2  0  0  1  0

目前尚不清楚您期望输出的类型,因此我将其留给您将DataFrame转换为您选择的输出。

答案 1 :(得分:0)

仅基于标准列表和词典的简单解决方案。它生成一个2D列表,然后很容易转换为CSV文件,而不是Excel加载。

d = {1:['c','d'],2:['a','h'],3:['a','b','b','f']}

cols = dict((c,n) for n,c in enumerate('abcdefgh'))
rows = dict((k,n) for n,k in enumerate('123'))
table = [[0 for col in cols] for row in rows]

for row, values in d.items():
    for col in values:
        table[rows[row]][cols[col]] += 1

print(table)

# output:
# [[0,0,1,1,0,0,0,0], [1,0,0,0,0,0,0,1], [1,2,0,0,0,1,0,0]]