[英]Writing multi-indexed data to an excel file with Python/Pandas
我想創建一個Excel電子表格,並為每個變量插入相同數量的行。 理想的結果看起來像圖中的A列和B列。
到目前為止我能做的只是插入一個名字(列D&E),並且不知道其余的正確枚舉。
這就是我所擁有的:
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")
我怎么能為所有人做到這一點? 謝謝。
您可以創建DataFrame
由numpy.tile
和numpy.repeat
,然后刪除重復的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)
這樣的事情應該有效:
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)
將食物寫入相應的部分,增加了行號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.