使用 Pandas 将过滤后的行复制到新的 sheet,有没有办法将旧行号附加到每个复制行的最后一个单元格?

Using Pandas to copy filtered rows to new sheet, is there a way to append the old row# to the last cell for each copied row?

我正在尝试通过 Python 过滤较大的 sheet,我将 .xlsx 读入新数据帧,过滤具有特定值的行,然后将每个匹配行输出到新数据框。

但是,我的问题是我想附加一个新列,该列仅包含来自原点 sheet 的“旧”行号。我不太确定如何有效地完成此操作。

有人能给我指出正确的方向吗?

import pandas as pd

df = pd.read_excel(path, sheet_name='Sheet 1')

matching_term_list = ['TRUE', 'FALSE']
column_name = 'True/False/NA'

df_filtered_command = df[df[col_name_type].isin(matching_term_list)]
df_filtered_command.columns = column_headers
df_filtered_command.head()

with pd.ExcelWriter('new_sheet.xlsx') as writer:
    df_filtered_command.to_excel(writer, sheet_name="Command", index=False)

过滤数据帧时,您可以重置索引而不是删除旧索引,这将添加一个新列“索引”。我将其重命名为“旧索引”:

df_filtered_command = df[df[col_name_type].isin(matching_term_list)].reset_index(drop=False).rename(columns={"index": "Old Index"})

如果实际的 Excel 行超出 1 左右(因为 header 等),您可以使用:

df_filtered_command["Old Index"] += 1