使用Python / Pandas将多索引数据写入excel文件

时间:2017-09-18 05:58:18

标签: python excel pandas multi-index xlwt

我想创建一个Excel电子表格,并为每个变量插入相同数量的行。理想的结果看起来像列A& B在图片中。

到目前为止,我所能做的只是插入一个名字(列D& E),并且不知道对其余部分进行适当的枚举。

name and food

这就是我所拥有的:

import xlwt, xlrd
import os

current_file = xlwt.Workbook()
write_table = current_file.add_sheet('Sheet1')

name_list = ["Jack", "David", "Andy"]
food_list = ["Ice-cream", "Mango", "Apple", "Cake"]

total_rows = len(name_list) * len(food_list)   # how to use it?

write_table.write(0, 0, "Jack")

for row, food in enumerate(food_list):
    write_table.write(row, 1, food)

current_file.save("c:\\name_food.xls")

我怎么能为所有人做到这一点?谢谢。

2 个答案:

答案 0 :(得分:4)

您可以按numpy.tilenumpy.repeat创建DataFrame,然后删除a列中的重复项:

df = pd.DataFrame({'a': np.repeat(name_list, len(food_list)),
                   'b': np.tile(food_list, len(name_list))})

df['a'] = np.where(df['a'].duplicated(), '', df['a'])
print (df)
        a          b
0    Jack  Ice-cream
1              Mango
2              Apple
3               Cake
4   David  Ice-cream
5              Mango
6              Apple
7               Cake
8    Andy  Ice-cream
9              Mango
10             Apple
11              Cake

列表理解的另一种解决方案:

df = pd.DataFrame({'a': [y for x in name_list for y in [x] + [''] * (len(food_list)-1)],
                   'b': food_list * len(name_list)})
print (df)
        a          b
0    Jack  Ice-cream
1              Mango
2              Apple
3               Cake
4   David  Ice-cream
5              Mango
6              Apple
7               Cake
8    Andy  Ice-cream
9              Mango
10             Apple
11              Cake

最后写to_excel

df.to_excel('c:\\name_food.xls', index=False, header=False)

答案 1 :(得分:3)

这样的事情应该有效:

import xlwt, xlrd
import os

current_file = xlwt.Workbook()
write_table = current_file.add_sheet('Sheet1')

name_list = ["Jack", "David", "Andy"]
food_list = ["Ice-cream", "Mango", "Apple", "Cake"]

for i, name in enumerate(name_list):
    write_table.write(i * len(food_list), 0, name_list[i])

    for row, food in enumerate(food_list):
        write_table.write(i * len(food_list) + row, 1, food)

current_file.save("c:\\name_food.xls")

重要的部分是

write_table.write(i * len(food_list), 0, name_list[i])

你说那个名字应该写在第0,4,8,12行......

另外,部分

write_table.write(i * len(food_list) + row, 1, food)

将食物写入由行号增加的相应部分。