首页 > 解决方案 > 设置从 1 到 n 的范围

问题描述

我正在遍历 Excel 表格,对其进行转换并将它们附加到单个数据集中。n张纸的长度可能会因文件而异,因此我需要设置从1(我不需要第一张纸)到n的范围。我该怎么做?

frame = pd.DataFrame()
list_ = []
for i in range(1:):
    df_1 = pd.read_csv(pd.read_excel(r'C:\Users\filippo.sebastio\OneDrive - ELEVATE\Target\Target Download 28 Feb\Quantitative data\SCHAEFER_Putian ZhangSheng\zhangsheng  --   RSAP Factory Metrics Tool- Hardcopy Form draft to publish 2018 12.xlsx', i , header = 4, index_col=1), index_col=None, header=0)
    worksheet_1 = workbook.sheet_by_index(1)
    df_1 = df_1.drop(df_1.index[0])
    df_1 = df_1.drop(df_1.index[-1])
    df_1 = df_1.drop(df_1.columns[0], axis=1)
    df_1 = df_1.dropna(axis=1, how='all')
    for col in  df_1.columns[0:3]:
        df_1[col] = pd.to_numeric(df_1[col], errors='coerce')
    df_1['mean'] = df_1.iloc[:, 0:3].mean(axis=1)
    df_1 = df_1[[ 'mean']]
    df_1_t = df_1.T
    df_1_t['Month'] = worksheet_1.cell(5, 2).value 
    df_1_t['Factory'] = worksheet_0.cell(2,2 ).value
    df_1_t['Factory_id'] = worksheet_0.cell(3,2 ).value
    df_1_t['Country'] = worksheet_0.cell(4,2 ).value
    df_1_t['Consultant'] = worksheet_0.cell(5,2 ).value

    list_.append(df1_t)

frame = pd.concat(list_)

我目前收到此错误

  File "<ipython-input-173-15bf28de4a3b>", line 4
    for i in range(1:):
                    ^
SyntaxError: invalid syntax

标签: pythonpandasrange

解决方案


':' 指的是 Python 中数组/列表的切片。例如:

>>> data = [1, 2, 3, 4, 5]
>>> print data[1:]
[2, 3, 4, 5]
>>> 

但你需要的是:

for i in range(n, m):  # no double point, only comma!

n从到的整数列表上的迭代器m-1


推荐阅读