簡體   English   中英

如何使用基於給定列表的python將數據添加到Excel工作表中的特定行/列?

[英]How to add data to specific row/column in an excel sheet using python based on a given list?

我有 python 代碼,它提供以下列表中的數據 = [作者,項目,編號]

我想將此數據添加到如下所示的 excel 文件中:原始excel文件 .

python 腳本將:

  1. 檢查列表中給出的Author Names是否在Author Names列中,如果不在,則添加姓名。
  2. 然后代碼將在與給定項目匹配的列中添加數字。

例如:

['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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM