使用xlsxwri将数据帧中的数据写入excel工作表时出错

2024-09-30 01:20:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,我正试图写到一个excel工作表使用xlsxwriter模块

以下是我的数据帧的外观:

prod_id,prod_name,price,units
prod_a,apple,100,10
prod_b,mango,10,123
prod_c,orange,12,14

我正在尝试将上述数据框写入excel,如下所示:

# Pulling data for the sheet
row = 1
col = 0

# Iterate through the array you have and unpack the tuple at each index
for elm1, elm2, elm3, elm4 in df:
    worksheet.write(row, col, elm1, number_format)
    worksheet.write(row, col + 1, elm2, number_format)
    worksheet.write(row, col + 2, elm3, number_format)
    worksheet.write(row, col + 3, elm4, number_format)
    row += 1

它抛出了一个错误

for elm1, elm2, elm3, elm4 in df:
ValueError: too many values to unpack (expected 4)

Tags: the数据formatnumberforcolprodexcel
1条回答
网友
1楼 · 发布于 2024-09-30 01:20:39

这个错误是因为,您使用多个变量在df上循环。相反,应该只使用一个变量

如果我理解正确,你可以像这样调整你的循环:

for row in df.itertuples():
    elm1,elm2,elm3,elm4 = row[1], row[2], row[3], row[4]
    worksheet.write(row, col, elm1, number_format)
    worksheet.write(row, col + 1, elm2, number_format)
    worksheet.write(row, col + 2, elm3, number_format)
    worksheet.write(row, col + 3, elm4, number_format)
    row += 1

这应该管用

相关问题 更多 >

    热门问题