如何在不丢失 Python 中的索引的情况下将行从 itertuples 附加到数据框?

How to append row from itertuples to dataframe withouth losing the index in Python?

我有以下问题:

我有一个 DataFrame df,它看起来像这样:

       eqpid  recpid   queuetime           trackintime         trackouttime
3723   A      XYZ      2017-01-01 03:14:58 2017-01-04 03:43:28 2017-01-04 03:43:33
...    ...    ...      ...                 ...                 ...

我正在使用 itertuples() 遍历此 DataFrame(我检查了矢量化和 .apply(),不幸的是在这里不起作用)。现在,除了其他操作:我想将该行(在我的理解中是 namedtuple)附加到另一个具有相同列的 DataFrame 并保留初始索引,所以它看起来像这样:

       eqpid  recpid   queuetime           trackintime         trackouttime
...    ...    ...      ...                 ...                 ...
3723   A      XYZ      2017-01-01 03:14:58 2017-01-04 03:43:28 2017-01-04 03:43:33

理论上,代码应该如下所示:

temp_df = pd.DataFrame(columns=df.columns)
for row in df.itertuples():
    ...
    temp_df.append(row)

但这不起作用,temp_df 仍然是空的。我也尝试过这样的事情:

temp_df = pd.DataFrame(columns=df.columns)
for row in df.itertuples():
    ...
    temp = pd.DataFrame([row],columns = row._fields)
    temp.set_index('Index', inplace = True)
    temp_df.append(temp)

但即使当我打印 temp 时它看起来像:

Index  eqpid  recpid   queuetime           trackintime         trackouttime
3723   A      XYZ      2017-01-01 03:14:58 2017-01-04 03:43:28 2017-01-04 03:43:33

temp_df 仍然是空的。有人可以提示我该怎么做或我的错误是什么吗?

提前谢谢大家!

尝试使用 'iterrows' 其中 returns 行作为索引的元组,系列:

for idx,ser in df.iterrows():
    ...
    temp_df = temp_df.append(ser)

系列本身也包含索引,因此索引对齐有效。

将行分配给数据框

temp_df = pd.DataFrame()
for row in df.itertuples(index=False):
    temp_df = temp_df.append(pd.DataFrame([row],columns = row._fields), ignore_index=True)

指定index=False忽略索引,ignore_index=True重置索引计数器