简体   繁体   English

如何以Excel形式附加到表格Pandas Dataframe

[英]How to append to a table in Excel form Pandas Dataframe

I am trying to get Python to take a dataframe or 2D numpy array and insert it into an existing table in Excel such that the table expands with my data in the appropriate columns 我试图让Python采用数据帧或2D numpy数组并将其插入Excel中的现有表中,以便表格在适当的列中展开我的数据

I tried using xlwings to paste the dataframe into Excel and expand it within the table. 我尝试使用xlwings将数据框粘贴到Excel中并在表格中展开它。 Two of my tables expand how I want with the data in the appropriate spot but one of my tables doesn't expands the data as though the table did not exist and continues writing it outside the table. 我的两个表扩展了我想要的数据在适当的位置,但我的一个表没有扩展数据,好像表不存在并继续将其写在表外。 I'm not sure if this has something to do with the problem table having a totals row at the bottom. 我不确定这是否与问题表有关,底部有一个总计行。

import numpy as np
import xlwings as xw

sheet = wb.sheets['sheet1']

"Inserts row of data above last row in table and moves n'th row to n-1'th row"
sheet.range('table1[#Data]').last_cell.api.EntireRow.Insert()
last_row = sheet.range('table1[#Data]).end('down').end('down').row
sheet.range('A{}:F{}'.format(last_row-1, last_row-1)).value = sheet.range('A{}:F{}'.format(last_row, last_row)).value

data = np.array(my_data)
sheet.range('A{}'.format(last_row)).value = data
sheet.range('A{}'.format(last_row)).expand('table')

I was hoping this would expand my 20x6 numpy array into columns A through F in the table but can't seem to get this to work. 我希望这会将我的20x6 numpy数组扩展到表中的A到F列,但似乎无法使其工作。 I'm not sure if there is some easier way of appending this data within the existing table so it expands properly, but I can't figure out how to do this. 我不确定是否有更简单的方法在现有表中附加这些数据,以便它正确扩展,但我无法弄清楚如何做到这一点。 I'd greatly appreciate any help 我非常感谢任何帮助

It would be better to convert the xlsx file to csv before adding any line. 在添加任何行之前将xlsx文件转换为csv会更好。

Then you can open the file for writing and add lines. 然后您可以打开文件进行编写并添加行。

cols = ['X1', 'X2', 'X3']
df['Y'] = df[cols].apply(lambda row: ','.join(row.values.astype(str)), axis=1)

with open('your_file.csv','wb') as f:
    for index, row in df.loc[:,Y].iterrows():
        f.write(row)
        f.write('\n')

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

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