使用组合工作表,遍历特定列,向新lis添加行

2024-05-29 10:43:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个excel工作簿,其中有多个工作表,所有工作表都有相同的列标题。我想遍历每个工作表中的一列,并将行添加到一个新列表(或列)。你知道吗

背景:每个工作表代表不同的农民社区,每个工作表的每一列都是一段人口数据。我给每个农民分配了一个代码,我想把所有这些代码都列在一个列表中。我知道我可以在excel中手动完成,但我正在尝试使用pandas、python

中某个工作表的示例修剪.xlsx文件如下所示: enter image description here


import pandas as pd
import numpy as np


sheets_pt = pd.read_excel(r"C:\Users\RRF\Desktop\pruning.xlsx",sheetname=None)
sheets_pt_read = pd.ExcelFile(r"C:\Users\RRF\Desktop\pruning.xlsx")

sheetnames_read = sheets_pt_read.sheet_names

codelist = []
for village in sheetnames_read:
    for code in sheets_pt[village]["Farmer Code"]:
        codelist.append(code)

在运行代码之后。我打印代码表和农民代码从前5页打印出来。然后出现下面的错误消息。。。你知道吗

这是我收到的错误消息:

KeyError回溯(最近一次调用) ~\Anaconda3\lib\site packages\pandas\core\索引\基本.py在get\u loc(self,key,method,tolerance)中 . . . KeyError:'农场主代码'

如果有人感兴趣的话,会非常乐意分享整个错误信息。你知道吗


Tags: 代码importptpandas列表readasxlsx
1条回答
网友
1楼 · 发布于 2024-05-29 10:43:18
import pandas as pd
import numpy as np

# read excel file into notebook assign to pro2019
pro2019 = pd.read_excel(path_to_file, sheet_name=None)

# concatenate all of the worksheets within the file removing the index 
# from individual sheets
df = pd.concat(pro2019, ignore_index=True)

# create empty list to store farmer codes
pro_codelist = []

# iterate through the df column titled "FARMER CODE"
# append each code to pro_codelist
for code in df["FARMER CODE"]:
    pro_codelist.append(code)

相关问题 更多 >

    热门问题