ValueError: Length mismatch - when tried to read multiple xlsx files with multiple sheets in pandas?

ValueError: Length mismatch - when tried to read multiple xlsx files with multiple sheets in pandas?

我正在尝试读取多个 xlsx 文件,每个文件有 51 张,我想读取、重新格式化并将它们连接到一个数据框中 pandas。但是,我能够正确读取一个 xlsx 和 51 张纸,但是当我使用相同的逻辑读取多个 xlsx 文件(每个文件有 51 张纸)时,出现以下错误:

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [31], in 12 print(names) 13 print(len(names)) ---> 14 src_df = (pd.concat({k: df.assign(State=df.columns[0]).set_axis(['County','Orientation','State'], axis=1) for k, df in pd.read_excel(xls, sheet_name = names).items()}).rename_axis(['ST', None], axis=0).reset_index(level=0)) 15 dfs.append(src_df)

Input In [31], in (.0) 12 print(names) 13 print(len(names)) ---> 14 src_df = (pd.concat({k: df.assign(State=df.columns[0]).set_axis(['County','Orientation','State'], axis=1) for k, df in pd.read_excel(xls, sheet_name = names).items()}).rename_axis(['ST', None], axis=0).reset_index(level=0)) 15 dfs.append(src_df) .. ..

ValueError: Length mismatch: Expected axis has 4 elements, new values have 3 elements

我目前的尝试:

这是我在尝试中使用的example data

VenueMap_Counties_04-02-15.xlsx
VenueMap_Counties_06-13-18.xlsx
VenueMap_Counties_11-04-19.xlsx

这是我尝试将那些 xlsx 包含多个工作表的文件读取到一个数据框中的尝试:

files = glob.glob('https://github.com/adamFlyn/test_rl/*.xlsx')
files_xlsx = [f for f in files if f[-4:] == 'xlsx']
if len(files_xlsx)>0:
    print("more than one xlsx files found")

# read multiple xlsx files into one
dfs = pd.DataFrame()
for f in files_xlsx:
    xls = pd.ExcelFile(f)
    sheetnames = xls.sheet_names[1:]
    print(sheetnames)
    print(len(sheetnames))
    src_df = (pd.concat({k: df.assign(State=df.columns[0]).set_axis(['County','Orientation','State'], axis=1) for k, df in pd.read_excel(xls, sheet_name = sheetnames).items()}).rename_axis(['ST', None], axis=0).reset_index(level=0))
    dfs.append(src_df)

有没有人知道如何解决此 valueError?有什么想法吗?

期望输出:

在我想要的输出中,我想要 Index(['ST', 'County', 'Orientation', 'State'], dtype='object') 作为最终数据框中的列。这是所需输出数据帧的前 5 行:

desired_outputDf.head().to_dict()= {'ST': {0: 'AK', 1: 'AK', 2: 'AK', 3: 'AK', 4: 'AK'},
 'County': {0: 'ALEUTIANS EAST',
  1: 'ALEUTIANS WEST',
  2: 'ANCHORAGE',
  3: 'BETHEL',
  4: 'BRISTOL BAY'},
 'Orientaion': {0: 'Plaintiff ',
  1: 'Plaintiff ',
  2: 'Neutral',
  3: 'Plaintiff ',
  4: 'Plaintiff '},
 'State': {0: 'Alaska', 1: 'Alaska', 2: 'Alaska', 3: 'Alaska', 4: 'Alaska'}}

谁能告诉我如何解决这个问题?有什么想法吗?谢谢

您的三个 xlsx 文件中有两个在 NC sheet 的 C 列中有一个杂散的反引号字符。修复这些,它应该可以工作。

更新:

这里是应该做你想做的代码:

files_xlsx='''
./VenueMap_Counties_04-02-15.xlsx
./VenueMap_Counties_06-13-18.xlsx
./VenueMap_Counties_11-04-19.xlsx
'''.split('\n')[1:-1]
import pandas as pd
dfs = pd.concat([
    df.rename(columns={df.columns[0]:'County'}).assign(
    State=df.columns[0], ST=ST)[['ST', 'County', 'Orientation', 'State']] for f in files_xlsx for ST, df in pd.read_excel(f, sheet_name=None).items() if ST != 'Master'])
print(f'shape: {dfs.shape}')
print(dfs.head())

输出:

shape: (9351, 4)
   ST          County Orientation   State
0  AK  Aleutians East  Plaintiff   Alaska
1  AK  Aleutians West  Plaintiff   Alaska
2  AK       Anchorage     Neutral  Alaska
3  AK          Bethel  Plaintiff   Alaska
4  AK     Bristol Bay  Plaintiff   Alaska