python - 使用 Pandas 打开 Excel 文件

标签 python excel

我正在尝试在 pandas 上打开我的 Excel 工作表。我在网上发现了一些有趣的tutorial 。但是,我在尝试组织标题时遇到了困难。

到目前为止,我已经遵循了代码:

import pandas as pd
pd.set_option('display.width', 300) 
fuel_file = (r'C:\Users\Sarah\Desktop\test\test2.xlsx')
xl = pd.ExcelFile(fuel_file)
print(xl.sheet_names)
fuel_df = xl.parse("Moon", header=[1], index_col=[0,1,2])
print(fuel_df.head())
print(fuel_df.columns)

weeknumbers_list = list(fuel_df.columns)
spacecustomers = fuel_df.iloc[1]

start_position = 0

for weeknr_pos in positions_weeknumbers:
    for pos in range(start_position, weeknr_pos):
        weeknumbers_list[pos] = weeknumbers_list[weeknr_pos]
    start_position = weeknr_pos + 1
    weeknumbers_list[weeknr_pos] = "Remove"

fuel_df.columns = weeknumbers_list
fuel_df.drop("Remove", axis=1, inplace=True)

问题出在:

for weeknr_pos in positions_weeknumbers:

错误信息:

**for weeknr_pos in positions_weeknumbers: TypeError: 'int' object is not iterable**

我不知道如何定义positions_weeknumbers

最佳答案

您收到错误“'int'对象不可迭代”,因为“positions_weeknumbers”将具有 int 值,并且您无法迭代 int 对象。您必须在 range() 函数内指定 int 对象,如下所示:

import pandas as pd
pd.set_option('display.width', 300) 
fuel_file = (r'C:\Users\Sarah\Desktop\test\test2.xlsx')
xl = pd.ExcelFile(fuel_file)
print(xl.sheet_names)
fuel_df = xl.parse("Moon", header=[1], index_col=[0,1,2])
print(fuel_df.head())
print(fuel_df.columns)

weeknumbers_list = list(fuel_df.columns)
spacecustomers = fuel_df.iloc[1]

start_position = 0

for weeknr_pos in range(positions_weeknumbers):
    for pos in range(start_position, weeknr_pos):
        weeknumbers_list[pos] = weeknumbers_list[weeknr_pos]
    start_position = weeknr_pos + 1
    weeknumbers_list[weeknr_pos] = "Remove"

fuel_df.columns = weeknumbers_list
fuel_df.drop("Remove", axis=1, inplace=True)

关于python - 使用 Pandas 打开 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59159385/

相关文章:

c# - 使用c#在excel中选择一个工作表

python - 注销页面在 Django 中不起作用

python - 我可以在一个脚本中打开一个文本文件,然后在子脚本中写入该文件吗?

python - 如何在Tensorflow中使用变量的旧值和新值?

python - 如何在 Python 中实现 R 的 p.adjust

javascript - 需要帮助将 vba excel 函数输出为日期值

python - 容器化 Python 命令行应用程序

excel - 用字符串中最后一个/后面的子字符串填充单元格

c# - 使用asp的excel行数

security - "50289 Can' t 执行操作,因为项目受到保护”但是为什么?