python to excel 路径_如何使用python将列添加到现有的Excel文件中?

here is my code:

import openpyxl, pprint

wb = openpyxl.load_workbook('/Users/sarahporgess/Desktop/SSA1.xlsx')

sheet = wb.get_sheet_by_name('Sheet1')

data = {}

for row in range(1,sheet.max_row+1):

date = sheet['A' +str(row)].value

gamma = sheet['B' +str(row)].value

theta = sheet['C' +str(row)].value

ratio = float(gamma)/float(theta)

resultFile = open('SSA2.csv' , 'w')

resultFile.write( pprint.pformat(date))

resultFile.write( pprint.pformat(gamma))

resultFile.write( pprint.pformat(theta))

resultFile.write( pprint.pformat(ratio))

print(ratio)

sheet['D1']=ratio

resultFile.close()

print('Done.')

my existing excel file currently has three columns: "date, gamma, theta". I want to add a fourth column called "ratio" that is the ratio of gamma/theta. How do I add another column to an existing excel document using python?

This code creates an excel document with the 4 elements printed into one cell

解决方案

It is easier to use the Pandas package

import pandas as pd

file_name = #Path to your file

df = pd.read_excel(file_name) #Read Excel file as a DataFrame

df['Ratio'] = df['Gamma']/df['Theta']

#Display top 5 rows to check if everything looks good

df.head(5)

#To save it back as Excel

df.to_excel("path to save") #Write DateFrame back as Excel file

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值