首页 > 解决方案 > 熊猫将索引复制到新列

问题描述

我正在尝试使用此处的答案将数据框 () 的索引复制newdf到新列 ( )但收到了臭名昭著的. 我在这里尝试了答案,它说要添加,但会引发更多警告。所有错误都在代码的最后一行抛出;如果代码在创建时停止,则不会出现错误。temp_indexSettingWithCopyWarning.loc[:, colname]newdf

复制索引的正确方法是什么?宁愿不重置索引,我希望索引来自df并且newdf是可以接受的。我只需要复制列来做其他事情。

示例可重现代码

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

标签: pandaspython-3.8

解决方案


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

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

推荐阅读