如何解决Pandas 将索引复制到新列
我正在尝试使用答案 here 将数据帧 (newdf
) 的索引复制到新列 (temp_index
),但收到了臭名昭著的 SettingWithCopyWarning
。我尝试了答案 here,它说要添加 .loc[:,colname]
,但它会引发更多警告。所有错误都在最后一行代码中抛出;如果代码在创建 newdf
时停止,则不会出现错误。
复制索引的正确方法是什么?不想重置索引,我希望 df
和 newdf
的索引是一致的。我只需要复制列来做其他事情。
可重现代码示例
col1 = [0,1,1]
col2 = [1,5,9,2,4,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]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。