将具有不同长度的数组的字典转换为Excel

时间:2020-05-28 21:57:46

标签: python pandas dataframe

我想像这样转换字典;

{'Application1': [nodename1, nodetier1, nodeid1],
 'Application2': [nodename2, nodetier2, nodeid2, nodename3, nodetier3, nodeid3]}

转换为excel格式,其中每3个项目多次打印字典键。理想情况下看起来像;

   Application    nodename    nodetier    nodeid
0  Application1   nodename1   nodetier1   nodeid1
1  Application2   nodename2   nodetier2   nodeid2
2  Application2   nodename3   nodetier3   nodeid3

1 个答案:

答案 0 :(得分:0)

检查此内容:

import pandas as pd

x = {
    'app1': [0, 1, 2],
    'app2': [0, 1, 2, 3, 4, 5],
    'app3': [0, 1, 2, 3, 4, 5, 6, 7, 8]
}

temp = []
for app in x:
    # chunk the list by the length of 3
    chunks = [x[app][i:i+3] for i in range(0, len(x[app]), 3)]
    # for all chunks add the value with the app name
    for chunk in chunks:
        temp.append(
            [app, *chunk]
        )

df = pd.DataFrame(temp, columns=('application', 'nodename', 'nodetier', 'nodeid'))

print(df)

给予:

  application  nodename  nodetier  nodeid
0        app1         0         1       2
1        app2         0         1       2
2        app2         3         4       5
3        app3         0         1       2
4        app3         3         4       5
5        app3         6         7       8

最后写入excel文件:

df.to_excel('excel_file')