我如何 select 基于 Python 中的列标题值的 excel 列

How do I select an excel Column based on the column heading value in Python

我有一个 python 数据框,我使用以下代码将其粘贴到 excel sheet 中:

df.to_excel(writer, columns = [Weeknum, Weeknum1, Weeknum2], sheet_name = 'QTY SLS', startrow = 5, startcol = 8, header = False , 索引 = 假)

数据框 weeknum、Weeknum1 和 Weeknum2 中的列 select 是代码中较早的输入(例如,Weeknum = Week 14)。因此,这些可能是 ['Week 16'、'Week 15'、'Week 14'] 作为示例。我的问题是如何 select 基于 Weeknum 输入的开始列。所以我粘贴的 Excel sheet 看起来像下面这样:

Store Week 10 Week 11 Week 12 Week 13 Week 14 Week 15 Week 16
A 1 4 4 2 1 5 4

所以我需要 Startcol 的代码在第 14 周开始(如果我将其放入输入)或第 10 周(如果我将其放入输入)。

希望这是有道理的。

您可以这样找到起始列:

import pandas as pd

# Toy dataframe
df = pd.DataFrame(
    {
        "Week 1": [1, 1, 1],
        "Week 2": [2, 2, 2],
        "Week 3": [3, 7, 3],
        "Week 4": [4, 8, 4],
        "Week 5": [7, 2, 9],
    }
)

Weeknum = "Week 3"  # Position in the df header index == 2
Weeknum1 = "Week 4"
Weeknum2 = "Week 5"

# Get the position of df column with value of Weeknum
print(list(df.columns).index(Weeknum))
# Outputs 2

因此,您可以这样修改代码:

df.to_excel(
    writer,
    columns=[Weeknum, Weeknum1, Weeknum2],
    sheet_name="QTY SLS",
    startrow=5,
    startcol=list(df.columns).index(Weeknum),
    header=False,
    index=False,
)