[英]Write pandas dataframe values to excel to specific cell in a specific sheet.
I have the following pandas dataframe: 我有以下熊猫数据框:
Name Sheet Row Column Value
0 V1 Sheet1 1 1 89
1 V2 Sheet1 2 1 104
2 V3 Sheet2 1 2 6
3 V4 Sheet3 3 3 -5
I want to save the Value in the sheet, row and column specified in the dataframe. 我想将值保存在数据框中指定的工作表,行和列中。 They are not in order and I don't know how many sheets there would be. 它们不整齐,我不知道会有多少张纸。 I could just go through each row and write using xlwt package 我可以遍历每一行并使用xlwt包编写
ws = wb.add_sheet('Sheet1')
ws.write(1, 1, 89)
I was wondering if I could achieve this using pandas API or any better approach? 我想知道是否可以使用pandas API或其他更好的方法来实现? Couldn't see pandas providing access to specific rows and columns of excel for writing. 无法看到熊猫提供对excel特定行和列的访问以进行编写。
One of the way is with the help of a for loop and iterrows()
ie 一种方法是借助for循环和iterrows()
即
writer = pd.ExcelWriter('out.xlsx')
for _,i in df.iterrows():
t_df = pd.DataFrame([i['Value']])
t_df.to_excel(writer, startcol=i['Column'],startrow=i['Row'], sheet_name=i['Sheet'], header=None, index=False)
writer.save()
Hope it helps. 希望能帮助到你。
I couldn't find an API which would directly write, however, I found xlwings
module to be quite helpful and intutive. 我找不到可以直接编写的API,但是,我发现xlwings
模块非常有用且直观。 Used the following code: 使用以下代码:
import xlwings as xw
wb = xw.Book('out.xls')
for index, row in result.iterrows():
wb.sheets[row['Sheet_Name']].range((row['Row'], row['Column'])).value = row['transformed_value']
wb.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.