繁体   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