繁体   English   中英

在python中写入Excel工作表

[英]writing to excel sheet in python

我试图通过使用熊猫成功地写到Excel工作表。 我不得不问: 首先,我尝试按列排序,但我不能。 我用df.sort_index,df.sortlevel都没有得到我想要的。 这是我的代码:

df = DataFrame({'Seq Label':['if >= 1','if >= 2','if >= 3','if >= 4','if >= 5','if >= 6','if >= 7'],
            'TP':[countTP, twocountTP, threecountTP, fourcountTP, fivecountTP, sixcountTP, sevencountTP], 
            'TN':[countTN, twocountTN, threecountTN, fourcountTN, fivecountTN, sixcountTN, sevencountTN], 
            'FP':[countFP, twocountFP, threecountFP, fourcountFP, fivecountFP, sixcountFP, sevencountFP], 
            'FN':[countFN, twocountFN, threecountFN, fourcountFN, fivecountFN, sixcountFN, sevencountFN]})
df.to_excel('Book10.xlsx', sheet_name='sheet1', index=False)

它给了我我不想要的输出:

    FN   FP Seq Label     TN    TP
0  123  125   if >= 1  20296  7671
1  123  125   if >= 2  17142  6274
2  123  125   if >= 3   3810  1307
3    7   11   if >= 4    419   213
4    1    4   if >= 5    127    74
5    0    0   if >= 6      0     0
6    0    0   if >= 7      0     0

我希望它按照我在df代码中的顺序排序表。 我希望将其排序为:

Seq Label   TP   TN    FP    FN

第二个问题如何在现有的Excel工作表上书写而不删除或写其他数据。 我试图使用不同的库。

import pandas as pd
import openpyxl
import xlrd

如果时间太长,我很抱歉。 我需要你的帮助

如何根据需要在数据帧df重新排列列,然后写入excel。 这样,您不必担心excel结束。
注意:列中的值是虚拟的。

>>> df = df[['Seq Label', 'TP', 'TN', 'FP', 'FN']]
>>> df
  Seq Label  TP  TN  FP  FN
0   if >= 1   1   1   1   1
1   if >= 2   2   2   2   2
2   if >= 3   3   3   3   3
3   if >= 4   4   4   4   4
4   if >= 5   5   5   5   5
5   if >= 6   6   6   6   6
6   if >= 7   7   7   7   7
>>> df.to_excel('Book10.xlsx', sheet_name='sheet1', index=False)

结果 在此处输入图片说明

首先对数据框进行排序,然后将其写入Excel。

df.sort_values(['Seq Label', 'TP', 'TN', 'FP', 'FN']).to_excel(...)

编辑

哦,您只想将列重新排列为所需的顺序。 尝试:

df[['Seq Label', 'TP', 'TN', 'FP', 'FN']].to_excel(...)

不能保证字典中项目的顺序。 如果您使用字典来构造数据框并考虑到目标顺序,则可以执行以下操作:

desired_order = [['Seq Label', 'TP', 'TN', 'FP', 'FN']]
df_order = [k for k in df if k in desired_order] + [k for k in df if k not in desired_order]
df = df[df_order]

如果密钥存在于数据框中,则将按所需顺序对数据框进行排序。 任何不按所需顺序排列的列都将附加到列的右侧。

from xlutils.copy import copy  # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
from xlwt import easyxf # http://pypi.python.org/pypi/xlwt

rb = open_workbook('file.xlrd',formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy
w_sheet.write(row, col, 'Value') 
wb.save(file_path)

在这里,您可以给出行号和列号,或用于循环以写入连续数据单元。 我用这个 对我来说是完美的工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM