pandas dataframe转换为excel与win32:numpy数据类型

2024-09-24 20:30:50 发布

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

我正在尝试使用win32将熊猫数据帧导出到excel。在

导出似乎只有在dataframe不包含numpy数据类型时才有效。在

如何将numpy数据类型转换为其COM变体?

这里有一个可复制的例子:

 import pandas as pd
 from win32com.client import Dispatch

 # Prepare data

 # data without numpy data type
 xdata1 = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
     'year' : [2000, 2001, 2002, 2002, 2001],
     'pop'  : [1.5, 1.7, 3.6, 2.4, 2.9 ]}
data1 = pd.DataFrame(xdata1, columns = ['year', 'state', 'pop'])
xT1 = [tuple(x) for x in data1.values]# # data to tuples

# data with numpy type
data2 = pd.crosstab(data1.state, data1.year)
xT2 = [tuple(x) for x in data2.values]  # data to tuples

# export the data 
 from win32com.client import Dispatch
 xlApp = Dispatch("Excel.Application")
 xlApp.Visible = 1
 xlApp.Workbooks.Add()
 xlSheet = xlApp.ActiveWorkbook.ActiveSheet

 # write to excel
  xlSheet.Cells(1,1).Value = 'Python Rules!'   # THIS WORKS AS EXPECTED

 # Write to a range : data without numpy data type
  FirstRow = 2
  FirstCol = 3
  LastRow = FirstRow + len(xT1) - 1 # Number of records
  LastCol =  FirstCol + len(xT1[0]) - 1        # Number of columns
   xlSheet.Range(xlSheet.Cells(FirstRow, FirstCol), xlSheet.Cells(LastRow , LastCol)).Value = xT1  # THIS WORKS AS EXPECTED 



# Write to a range : data WITH  numpy data type
FirstRow = 2
FirstCol = 5
LastRow = FirstRow + len(xT2) - 1 # Number of records
LastCol =  FirstCol + len(xT2[0]) - 1        # Number of columns
xlSheet.Range(xlSheet.Cells(FirstRow, FirstCol), xlSheet.Cells(LastRow , LastCol)).Value = xT2  

这行产生一个错误

类型错误:类型为'数字.int64'无法转换为COM变量(但可以获取此对象的buffer())

附言:在有人提出要求之前(或者建议另一种出口到出口的方式)。我故意使用win32,因为这是我发现写入现有的、预先准备好的excel文件并保留样式的唯一方法

p.p.S.: 受此posting的启发,我想出了一个解决方案,即更改数据帧中每个元素的类型 我相信还有更好的方法

^{pr2}$

Tags: tonumpynumberdatalentypecellsdata1