[英]Subtract cell in one column from the one prior in xlsx file in Python
[英]How to subtract cell values from one column with cell values from another column in xlsx files using python
我想從一列中減去單元格值與另一列中的單元格值,並將總和寫入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稱為生成器,而不是可訂閱者。 我不確定如何搜索和閱讀excelfile,同時使其可訂閱,以便可以寫入它。 有人可以幫幫我嗎?
這是我的代碼:
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很新。
首先通過DataFrame
從excel創建read_excel
。
然后需要減去2.
有4
列:
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]
也許還有助於檢查文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.