[英]How to iterate over a Row or Column of an Excel sheet using Python and look for specific value in cells?
[英]How to add data to specific row/column in an excel sheet using python based on a given list?
我有 python 代碼,它提供以下列表中的數據 = [作者,項目,編號]
我想將此數據添加到如下所示的 excel 文件中: .
python 腳本將:
Author Names
是否在Author Names
列中,如果不在,則添加姓名。例如:
['author2', 'Oranges', 300], 300 將添加到 author2 行的 Oranges 列中。
如果此人再次添加一個列表,例如 ['author2', 'Oranges', 500] 並且該項目的輸入已經存在,則該數字將加在一起,因此最終結果為 800。
我該如何開始? 我對如何讀取列/行以找到插入內容的位置感到困惑。
以下是您可能如何做到的一個示例:
import csv
from collections import defaultdict
# Make a dictionary for the authors, that will automatically start all the
# values at 0 when you try to add a new author
authors = defaultdict(lambda: dict({'Oranges':0, 'Apples':0, 'Peaches':0}))
# Add some items
authors['author1']['Oranges'] += 300
authors['author2']['Peaches'] += 200
authors['author3']['Apples'] += 50
authors['author1']['Apples'] += 20
authors['author2']['Oranges'] += 250
authors['author3']['Apples'] += 100
# Write the output to a csv file, for opening in Excel
with open('authors_csv.csv', 'w', newline='') as file:
writer = csv.writer(file)
# Write Header
writer.writerow(['Author Names', 'Oranges', 'Apples', 'Peaches'])
for key, val in authors.items():
writer.writerow(
[key,
val['Oranges'], val['Apples'], val['Peaches']
])
有關寫入 CSV 的更多詳細信息,您可以在此處查看文檔: https : //docs.python.org/3/library/csv.html
或者,只需使用 DuckDuckGo 或您最喜歡的搜索引擎進行搜索。
很可能看起來您的電子表格存儲在外部,並且您想從列表格式 [作者、項目、編號] 中讀取一些新數據。
Python pandas
非常適合這一點。 這將讀取數據文件,我們稱之為authorVolumes.xlsx
。 這假設電子表格已經在我們正在處理的文件夾中,並且看起來就像在您的第一張圖片中一樣。 此外,這些項目僅限於電子表格中的項目,因為您在問題中沒有提及。
import pandas as pd
df = pd.read_excel('authorVolumes.xlsx', index_col='Author Names').fillna(0)
print(df)
Author Names Oranges Apples Peaches
author1 0 0 0
author2 0 0 0
author3 0 0 0
author4 0 0 0
author5 0 0 0
現在讓我們定義一個函數來處理更新。
def updateVolumes(author, item, amount):
try:
df.loc[author][item] += amount
except KeyError:
df = pd.concat([df,pd.DataFrame([amount], index=[author], columns=[item])]).fillna(0)
處理第一次更新的時間: ['author2', 'Oranges', 300]
author, item, amount = ['author2', 'Oranges', 300]
updateVolumes(author, item, amount)
現在處理一個作者不在的地方:
author, item, amount = ['author10', 'Apples', 300]
updateVolumes(author, item, amount)
完成后,我們可以將 excel 文件保存回文件系統。 df.to_excel('authorVolumes.xlsx')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.