Pandas 将索引复制到新列

Pandas copy index to new column

我正在尝试使用答案 but am receiving the infamous SettingWithCopyWarning. I tried the answer 将数据帧 (newdf) 的索引复制到新列 (temp_index),它表示要添加 .loc[:, colname] 但它会引发更多警告。所有错误都在最后一行代码抛出;如果代码在创建 newdf 时停止,则不会出现错误。

复制索引的正确方法是什么?不想重置索引,我希望 dfnewdf 中的索引是可以接受的。我只需要复制栏来做其他事情。

可重现代码示例

col1 = [0,1,1,0,0,0,1,1,1]
col2 = [1,5,9,2,4,2,5,6,1]
df = pd.DataFrame(list(zip(col1, col2)), columns =['col1', 'col2'])
newdf = df[df.col2 >= 3]
display(df, newdf)
newdf.loc[:, 'temp_index'] = newdf.index

错误

C:\Users\...\lib\site-packages\pandas\core\indexing.py:845: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self.obj[key] = _infer_fill_value(value)
C:\Users\...\lib\site-packages\pandas\core\indexing.py:966: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self.obj[item] = s

您在最后一行中设置 temp_index 列的方式没有任何问题。问题正如警告中所说。你到底想达到什么目的?要避免此警告,请执行 newdf = df[df.col2 >= 3].copy()。请注意,您正在使用布尔键进行索引,AFAIK 无论如何都会创建一个副本,因此上述内容不会增加您的内存占用。 如果您确实想将索引插入 df 但仅插入行的子集,请尝试

key = df.col2 >= 3
df = df.loc[key, 'temp_index'] = df.index[key]