gpt4 book ai didi

python - 如何使用 python 从 xlsx 文件中的一列中减去另一列中的单元格值

转载 作者:行者123 更新时间:2023-11-30 22:34:07 25 4
gpt4 key购买 nike

我想用一列中的单元格值与另一列中的单元格值相减,并将总和写入 Excel 文件中的新列。然后我希望将总和(如果不等于 0)添加到列表中以供以后使用。我的 Excel 文件中的数据结构如下:

Name | Number | Name1 | Number1
Name2 | Number2 | Name3 | Number3
....
Namex | Numberx | Namey |Numbery

我想将数字相减,然后将总和添加到新列中,如下所示:

Name| Number | Name1 | Number1 | Sum of (Number - Number1)

我尝试使用 openpyxl 来执行此操作,但我真的很困惑,因为这些文档与早期版本的 Python 和新版本有很大不同。我正在使用 Python 3.4。我很高兴收到您推荐我使用哪个模块的建议。到目前为止,我的代码给了我错误,因为我将 excelfile 称为生成器,而不是可下标的。我不知道如何搜索和读取 Excel 文件,同时使其可下标,以便可以对其进行写入。有人可以帮我吗?

这是我的代码:

from openpyxl import Workbook, load_workbook

def analyzexlsx(filepath):
numbers = []
excel_input = load_workbook(filepath)
filepath = [pth for pth in Path.cwd().iterdir()
if pth.suffix == '.xlsx'] #Want to iterate through several excel files in a folder.
ws = excel_input.active
cols = tuple(ws.columns)
col_b = cols[1]
col_e = cols[4]
for j, k in zip(col_e, col_b):
if None:
print('None')
equally = (int(j.value) - int(k.value)) #line 13, error. Trying to subtract column cell values.
if equally != 0: #If the columns sum is not equal to 0, it is to be added to the numbers list.
numbers.append(j.row)

else:
pass

col1 = []
col2 = []
col4 = []
col5 = []
col7 = []
col8 = []

mainlist = []
try:
for row in numbers:
col1.append(str(ws.cell(row=row, column=1).value))
col2.append(str(ws.cell(row=row, column=2).value))
col4.append(ws.cell(row=row, column=4).value)
col5.append(ws.cell(row=row, column=5).value)
col7.append(ws.cell(row=row, column=7).value)
col8.append(ws.cell(row=row, column=8).value)
finally:
for i, j, k, l, m, n in zip(col1, col2, col4, col5, col7, col8):
mainlist.append(i + ", " + j + ", " + k + ", " + l + ", " + m + ", " + n)
return mainlist

Traceback (most recent call last):
Line 13, in analyzexlsx
equally = (int(j.value) - int(k.value))
TypeError: int() argument must be a string or a number, not 'NoneType

我真的很高兴得到答案,因为我已经为此工作了很长一段时间,但现在我陷入了困境。我对 Python 还很陌生。

最佳答案

首先通过 read_excel 从 excel 创建 DataFrame .

然后需要用 4 列减去 2.:

df = pd.read_excel('file.xlsx')

#select by column name
df['E'] = df['B'] - df['D']
<小时/>
#select by positions, but python count from 0 so for 2. column need 1
df['E'] = df.iloc[:, 1] - df.iloc[:, 3]

也许还可以帮忙检查documentation .

关于python - 如何使用 python 从 xlsx 文件中的一列中减去另一列中的单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44946458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com